Python培训
400-996-5531
本代码测试采用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 '
免责声明:内容和图片源自网络,版权归原作者所有,如有侵犯您的原创版权请告知,我们将尽快删除相关内容。
填写下面表单即可预约申请免费试听! 怕学不会?助教全程陪读,随时解惑!担心就业?一地学习,可全国推荐就业!
Copyright © 京ICP备08000853号-56 京公网安备 11010802029508号 达内时代科技集团有限公司 版权所有
Tedu.cn All Rights Reserved