字符串是python中非常重要的数据类型,熟练使用这种数据类型对编程开发非常重要。下文将从以下4个方面来阐述字符串的详细使用方法
1 字符串类型的表示
2 转义字符
3 字符串操作符
4 常用的字符串方法
一,字符串类型的表示
字符串有三种表示方法,可以由一对单引号表示,也可以由一对双引号号表示,还可由一对三引号表示。
>>> 'long long ago'
'long long ago'
>>> "long long ago"
'long long ago'
>>> '''long long ago'''
'long long ago'
当然,值得注意的一点时,python中的#只可以用于单行注释,而''' '''常常可以用于多行注释,这是完全可行的。
'''this is a program that can
be used to solve some problems'''
def mt(a,b):
if a>b:
return a
else:
return b
二,转义字符
对于英语句子I am a student,我们往往会将I am 写为I'm,这时,想要输出上面的句子便需要用转义字符(也可以用其它方法)。
>>> 'I'm a student'
"I'm a student"
转义字符包含一个倒斜杠(),紧跟着是想要添加到字符串中的字符,尽管它包含两个字符,但大家公认它是一个转义字符。例如,单引号的转义字符是'。
常见的转义字符如下:
| ' | 单引号 |
| '' | 双引号 |
| t | 制表符 |
| n | 换行符 |
| \ | 倒斜杠 |
| r | 回车符 |
三,字符串操作符
| str1+str2 | 合并两个字符串 |
| str*n | 将字符串复制n次 |
| str1 in str2 | 判断str1是否在str2中 |
| str[i] | 索引 |
| str[i:j] | 切片,返回i到j的字符,不含j |
>>> 'math'+'math'
'mathmath'
>>> 'math'*3
'mathmathmath'
>>> 'apple' in 'appletree'
True
>>> str1='a piece of cake'
>>> str1[2]
'p'
>>> str1[0:3]
'a p'
四 ,常用的字符串方法
| upper() | 字符转换为大写 |
| lower() | 字符转换为小写 |
| isuper() | 判断字符是否全为大写 |
| islower() | 判断字符是否全为小写 |
>>> str1='tree and apple'
>>> str1.upper()
'TREE AND APPLE'
>>> 'TREE AND APPLE'.lower()
'tree and apple'
>>> 'Apple'.islower()
False
>>> 'TREE'.isupper()
True
startswith():所调用字符串以该方法传入的字符串开始则返回True
endswith():所调用字符串以该方法传入的字符串结束则返回True
>>> 'Hello world'.startswith('Hello')
True
>>> 'Hello world'.startswith('llo')
False
>>> 'Hello world'.endswith('Hello')
False
>>> 'Hello world'.endswith('world')
True
join():将列表内容组合为字符串
形式:'字符'.join(列表)
>>> ' '.join(['apple','and','tree'])
'apple and tree'
>>> 't'.join(['apple','and','tree'])
'appletandttree'
split()用法见文章:python的split()函数!
len():返回字符串的长度
str():将传入参数转换为字符串
chr():将传入的Unicode编码转换为对应的字符
ord():将传入字符转换为对应的Unicode编码
>>> len('appletree')
9
>>> str(1)
'1'
>>> chr(30)
'x1e'
>>> chr(96)
'`'
>>> chr(97)
'a'
>>> ord('a')
97
rjust(),ljust(),center()方法对齐文本
rjust():右对齐
ljust():左对齐
center():居中对齐
>>> 'appletree'.rjust(15,'*')
'******appletree'
>>> 'appletree'.ljust(15,'*')
'appletree******'
>>> 'appletree'.center(15,'*')
'***appletree***'
很显然,这是用*号作为填充字符,同时第一个参数则代表长度,该长度为总长度,则填充字符的长度为总长度减去原字符串长度。
调用格式:字符串.方法(长度,填充字符)
lstrip():删除字符串左边的空白字符
rstrip():删除字符串右边的空白字符
strip():删除字符串开头和末尾的空白字符
>>> ' apple and tree '.rstrip()
' apple and tree'
>>> ' apple and tree '.lstrip()
'apple and tree '
>>> ' apple and tree '.strip()
'apple and tree'
用pyperclip模块拷贝粘贴字符串。pyperclip()模块有copy()和paste()函数,可以向计算机的剪贴板发送文本,或从它接收文本。
>>> import pyperclip
>>> pyperclip.copy('appletree')
>>> pyperclip.paste()
'appletree'
当然,如果我们在其它地方已经复制过某些内容,此时,该内容则在剪切板上,在python编辑器中输入 pyperclip.paste(),则会返回剪切板的内容。



