联系方式

咨询热线:400-998-6158

点击此处免费预约试听课程»

常见问题
学习资讯
师资介绍
学习资讯

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 "<input>", line 1, in <module>

ValueError: substring not found

3.count 返回字符串在目标字符串中出现的次数

string = "i love python very much "

string.count("o")

2

string.count("python")

1

string.count(" ")

5

string.count("study")

0

4.replace 将字符串中指定的字符串用其它字符串进行替换

string = "i love python very much "result1 = string.replace("python","girl")

result1

'i love girl very much '#本行代码中的2指得是较多使用—_替换两个空格,第三个参数不写默认为0

result2 = string.replace(" ","_",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

9.endswith 检查字符串结尾是否包含指定字符串,和startswith类似

string = "i love python very much "result11 = string.endswith(" ")

result11

True

result12 = string.endswith("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'

14.center 返回一个原字符串居中对齐,并使用空格来填充剩余位置的字符串

string =" hello"result17 = string.center(9)

result17

' hello '
学校联系方式

更多培训课程,学习资讯,课程优惠等学校信息,请进入 长春南关区java培训长春宽城区C语言培训 网站详细了解,免费咨询电话:400-998-6158

相关课程