-
字符串的常用操作
index():查找子串substr第一次出现的位置,如果查找的字串不存在,则抛出ValueError.
rindex():查找子串substr最后一次出现的位置,如果查找的字串不存在,则抛出ValueError.
find():查找子串substr第一次出现的位置,如果查找的字串不存在,则返回-1.
rfind():查找子串substr最后一次出现的位置,如果查找的字串不存在,则返回-1.
s=‘hello,hello’
print(s.index(‘lo’))
print(s.rindex(‘lo’))
print(s.find(‘lo’))
print(s.rfind(‘lo’))
运行→
3
9
3
9 -
字符串中的大小写转换
upper():把字符串中所有的字符都转化成大写字母;
lower():把所有的字符都转化成小写字母;
swapcase():把所有的大写字符转化成小写字符,所有的小写字符转化成大写字符;
capitalize():把第一个字符转化成大写,把其余字符都转化成小写;
title():把每个单词的第一个字符转化成大写,把每个单词的剩余字符转化成小写。
s=‘hello,python’
a=s.upper()
print(a,id(a))
print(s,id(s))
b=s.lower()
print(b,id(b)) #转换之后产生一个新的字符串对象(地址不同)
print(s,id(s))
print(b==s) #内容一样
print(b is s) #地址不同,没有驻留
运行→
HELLO,PYTHON 1641050717424
hello,python 1641050717488 #转化后地址发生改变
HELLO,PYTHON 2050325396720
hello,python 2050325396784
hello,python 2050325444144
hello,python 2050325396784
True
False
s2=‘heLlo,Python’
print(s2.swapcase())
print(s2.capitalize())
print(s2.title())
运行→
HElLO,pYTHON
Hello,python
Hello,Python
- 字符串中的对齐操作
s=‘hello,Python’
print(s.center(20,‘') #s是12个字符,20-12=8,所有左右各4个,居中对齐
print(s.ljust(20,’')) #左对齐,最后用8个补充指定宽度20
print(s.ljust(10)) #设置宽度小于20,则返回原字符串
print(s.ljust(20)) #左对齐,指定填充符默认是空格
运行→
hello,Python
hello,Python********
hello,Python
hello,Python
print(s.rjust(20,‘')) #右对齐,前面用8个填充
print(s.zfill(20)) #右对齐,zfill(),只能指定宽度,前面默认用0对齐
print(’-8990’.zfill(9)) #指定宽度是9,8990是4为,9-4=5,使其右对齐,前面加上-号再补4个0凑够5位
运行→
********hello,Python
00000000hello,Python
-00008990
-
字符串劈分操作(输出的是列表)
s=‘hello world Python’
lst=s.split()
print(lst) #未指出劈分符默认是空格,输出是列表
s1=‘hello|world|Python’
print(s1.split()) #没有空格,则未劈分
print(s1.split(sep=‘|’)) #指定劈分符是|
print(s1.split(sep=‘|’,maxsplit=1)) ##指定劈分符是|,且最大劈分次数是1
运行→
[‘hello’, ‘world’, ‘Python’]
[‘hello|world|Python’]
[‘hello’, ‘world’, ‘Python’]
[‘hello’, ‘world|Python’] -
判断字符串的方法
注:合法的标识符是由字母、数字、下划线组成,但第一个字符不能是数字。Pycharm中可以用汉字做变量名。
s=‘hello,python’
print(‘1.’,s.isidentifier()) #’,’号不符合标识符的要求,故为False
s2=‘hello’
print(‘2.’,s2.isidentifier())
print(‘3.’,‘张三_’.isidentifier()) #Pycharm中可以用汉字做变量名,所以‘张三’是符合标识符的
print(‘4.’,‘张三_123’.isidentifier())
print(‘5.’,‘123_张三’.isidentifier())
运行→
5. False
6. True
7. True
8. True
9. False
print(‘6.’,‘\t’.isspace()) #判断是否由空白字符组成(包括回车、换行、水平制表符)
print(‘7.’,‘abc’.isalpha()) #判断是否全部由字母组成
print(‘8.’,‘张三’.isalpha()) #汉字可以做变量名,记住是True
print(‘9.’,‘张三1’.isalpha()) #1不是字母
10. True
11. True
12. True
13. False
print(‘10.’,‘123’.isdecimal()) #判断字符串是否全由十进制数字组成
print(‘11.’,‘999九’.isdecimal()) #九不是十进制数字
print(‘12.’,‘ⅠⅡⅢ’.isdecimal()) #罗马数字不是十进制数字
10. True
11. False
12. False
print(‘13.’,‘123’.isnumeric()) #判断是否全部由数字组成
print(‘14.’,‘123四’.isnumeric()) #中文四也是数字,故为True
print(‘15.’,‘123si’.isnumeric()) #si不是数字
print(‘16.’,‘ⅠⅡⅢ’.isnumeric()) #罗马数字也是数字
13. True
14. True
15. False
16. True