python获取字符串⾸字母_Python字符串常⽤操作命令
本代码测试采⽤python3解释器
1.find string = "i love python very much "
检查字符串是否包含在string中,如果包含则返回字符串开始的下标(索引),如果不包含则返回-1
string = "i love python very much "
string.find("love")
2
string.find("study")
-1
rfind 和find类似,不过是从右侧开始查,因为有的字符串在原字符串中会有多个,但返回值只有第⼀个,所有rfind是属于右侧优先原则2.index 作⽤和find⼀样,但如果不包含字符串则抛异常(报错),rindex和rfind类似
string = "i love python very much "
string.index("love")
2
string.index("study")
Traceback (most recent call last):
File "", line 1, in
ValueError: substring not found
string = "i love python very much "
2
1
5
string = "i love python very much "result1 = place("python","girl")
result1
'i love girl very much '#本⾏代码中的2指得是最多使⽤—_替换两个空格,第三个参数不写默认为0
result2 = place(" ","_",2)
result2
'i_love_python very much '
5.split 以指定字符分割切⽚字符串,返回值为list列表,⽆参数默认为空格分割
string = "i love python very much "#不写参数默认使⽤空格分割,且连续多个空格视为⼀个#若空格在⾸部或尾部则不再往两端分割result3 = string.split()
result3
['i', 'love', 'python', 'very', 'much']
result4 = string.split(" ")
result4
['i', 'love', 'python', 'very', 'much', '']
result5 = string.split("e")
result5
['i lov', ' python v', 'ry much ']
6.capitalize 将字符串⾸字母转换成⼤写
string = "i love python very much "result6 = string.capitalize()
result6
'I love python very much '
7.title 将字符串中每个单词的⾸写
result7 = string.title()
result7'I Love Python Very Much '
8.starswith 检查字符串开头是否包含指定字符串
string = "i love python very much "result9 = string.startswith("i")
result9
True
result10 = string.startswith("a")
result10
False
string = "i love python very much "result11 = dswith(" ")
result11
True
result12 = dswith("ab")
result12
False
10.lower 将字符串中所有的⼤写字母转化为⼩写
string = "i love python very much"result13 = string.lower()
result13'i love python very much'
11.upper 将字符串中所有的⼩写字母转化为⼤写,和lower相反的作⽤
string = "i love python very much"result14 = string.upper()
result14'I LOVE PYTHON VERY MUCH'
12.ljust 返回⼀个原字符串左对齐,并使⽤空格来填充剩余位置的字符串
string =" hello"result15 = string.ljust(10)
result15
'hello '
13.rjust 返回⼀个原字符串右对齐,并使⽤空格来填充剩余位置的字符串
string =" hello"result16 = string.rjust(10)
result16
' hello'
< 返回⼀个原字符串居中对齐,并使⽤空格来填充剩余位置的字符串
string =" hello"result17 = (9)
find查命令的使用result17
' hello '
免责声明:内容和图⽚源⾃⽹络,版权归原作者所有,如有侵犯您的原创版权请告知,我们将尽快删除相关内容。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。