Python 字符串操作基础

1.Python 字符串

字符串可以看做是由单个文本字符构成的列表,每个字母构成一个列表元素,可以用下标取值,切片,用于for循环,用len()函数

name = 'Zophoie'
name[2]
name[-3]
name[0:3]

'Zo'in name

'ZO'in name
len(name)

'ZOO'not in name
True
for i in name:
    print('*'*(len(name)))
*******
*******
*******
*******
*******
*******
*******

1.1 可变和不可变数据类型

字符串不可变,只能通过 切片 和 连接 构造新的字符串

sentence = 'Zophie loves me'

new = sentence[:7]+'hates'+sentence[-3:]

new
'Zophie hates me'

2.字符串操作

2.1 处理字符串

## 2.1.1 转义字符
### \t 表示制表符,相当于 tab键
print ('I\'m tall but dumb “baby”,that\'s what they call me\nI don\'t really care ,honestly speaking\nThis is a test \t \\')

## 2.1.2 原始字符串
###引号前加 r ,忽略所有转义字符
print('I\'m lonely')
print(r'I \'m lonely' )

## 2.1.3 三重引号的多行字符串
### “ 三重引号” 之间的所有引号、 制表符或换行, 都被认为是字符串的一部分。
print('''what if
I'm powerful enough 
to be weak
''')

# 2.1.4 多行字符串可以用来注释
'''
三个引号就可以
做多行注释了吗
似乎不是一个好的方法
'''
I'm tall but dumb “baby”,that's what they call me
I don't really care ,honestly speaking
This is a test   \
I'm lonely
I \'m lonely
what if
I'm powerful enough 
to be weak

'\n三个引号就可以\n做多行注释了吗\n似乎不是一个好的方法\n'
#2.1.5 字符串下标与切片
spam = 'Hello,bae'
spam[3]

#2.1.6 字符串 in 和 not in 操作符
'Hello' in spam
True

2.2 有用的字符串方法

## 字符串方法 upper() , lower(), isupper(), islower()

spam = spam.upper()
spam
spam.islower()
spam.lower().islower()
True

2.2.1 isX 字符串方法

方法 true when
isalpha() 非空 仅字母
isalnum() 非空 仅字母 数字
isdecimal() 非空 仅数字
isspace() 非空 仅空格、换行、制表符
istitle() 仅包含大写开头其余小写的单词(标题)

可以用来验证用户输入内容

2.2.2 字符串方法 startswith() endswith()

'Hello world'.startswith('He')
True
'Hello world'.endswith('12')
False

2.2.3 字符串方法 join() split()

','.join(['I','like','you'])
'I,like,you'
' '.join(['I','miss',"you"])
'I miss you'
'My name is Carol'.split()
['My', 'name', 'is', 'Carol']
'Iabcloveabcyouabcdarling'.split('abc')
['I', 'love', 'you', 'darling']
' '.join('Iabcloveabcyouabcdarling'.split('abc'))  #join split 结合
'I love you darling'

2.2.4 rjust() , rjust() , center() 对齐文本

'hello world'.rjust(20)   #右对齐,
'         hello world'
'hello'.ljust(20,'+')    #左对齐
'+++++++++++++++hello'
'bazinga'.center(20,'=')  #居中
'======bazinga======='

2.2.5 strip() , rstrip() , lstrip() 删除空白字符串

'  Hello,world  '.strip()         #删除两边空白字符
'Hello,world'
'asbdiabafiaobfa'.strip('absf')   #删除两边指定字符,与顺序无关
'diabafiao'

2.2.6 用 pyperclip() 模块拷贝粘贴字符串

pyperclip 模块有 copy()和 paste()函数, 可以向计算机的剪贴板发送文本, 或从它接收文本。
将程序的输出发送到剪贴板, 使它很容易粘贴到邮件、文字处理程序或其他软件中。
pyperclip 模块不是 Python 自带的,要安装它.

import pyperclip
pyperclip.copy('What\'s the world like')
pyperclip.paste()
"What's the world like"
pyperclip.paste()
"'For example, if I copied this sentence to the clipboard and then called\r\npaste(), it would look like this:"

参考文献
《Python编程快速上手–让繁琐工作自动化》

发布了30 篇原创文章 · 获赞 63 · 访问量 11万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章