python之字符串操作(一)

测码学院

 

1、首先定义字符串:name="how do you does and how are you!"find ===》格式:name.find(str,start=0,end=len(name))说明:检测str是否包含在name中,如果是返回开始的索引值,否则返回-1rfind ===》格式:name.rfind(str,start=0,end=len(name))说明:类似于find()函数,不过是从右边开始查找.In [13]: name="how do you does and how are you!"In [14]: name.find("are")Out[14]: 24In [15]: name.find("you")Out[15]: 7In [16]: name.rfind("you")Out[16]: 28In [17]: name.find("you",0,6)Out[17]: -1In [18]: name.find("does",0,20)Out[18]: 11

测码学院,python自动化测试视频教程

2、index ===>格式:name.index(str,start=0,end=len(name))说明:跟find()方法一样,不过如果str不在 name中会报一个异常rindex ===》格式:name.rindex(str,start=0,end=len(name))说明:类似于 index(),不过是从右边开始.In [19]: name.index("are")Out[19]: 24In [20]: name.index("you")Out[20]: 7In [21]: name.index("does",0,20)Out[21]: 11In [22]: name.index("does",0,9)---------------------------------------------------------------------------ValueError Traceback (most recent call last)<ipython-input-22-2d1e8ee1523c> in <module>()----> 1 name.index("does",0,9)ValueError: substring not found

测码学院,python自动化测试视频教程

3、count ===》格式:name.count(str,start=0,end=len(name))说明: str在start和end之间 在 name里面出现的次数In [23]: name.count("you")Out[23]: 2In [24]: name.count("you",0,15)Out[24]: 1

测码学院,python自动化测试视频教程

4、replace ===》name.replace(str1,str2,name.count(str1))说明:把 name中的 str1 替换成 str2,如果 count 指定,则替换不超过 count 次.In [25]: name.replace("are","is")Out[25]: 'how do you does and how is you!'In [26]: name.replace("you","he",name.count("you"))Out[26]: 'how do he does and how are he!'

测码学院,python自动化测试视频教程

5、split ===>格式:name.split(str="",2)说明:以 str 为分隔符切片 name,如果 maxsplit有指定值,则仅分隔 maxsplit 个子字符串In [27]: name.split(" ")Out[27]: ['how', 'do', 'you', 'does', 'and', 'how', 'are', 'you!']In [28]: nameOut[28]: 'how do you does and how are you!'In [29]: name.split(" ",2)Out[29]: ['how', 'do', 'you does and how are you!']In [30]: name.split(" ",3)Out[30]: ['how', 'do', 'you', 'does and how are you!']In [31]: name.split(" ",4)Out[31]: ['how', 'do', 'you', 'does', 'and how are you!']

测码学院,python自动化测试视频教程

6、capitalize ===>格式:name.capitalize()说明:把字符串的第一个字符大写In [32]: name.capitalize()Out[32]: 'How do you does and how are you!'

测码学院,python自动化测试视频教程

更多关于python自动化测试学习资料可加博主qq:1993712276,或者去测码官网查看

原文地址:https://www.cnblogs.com/cema/p/13276160.html