Home >Backend Development >Python Tutorial >Inventory of 16 common operations methods on Python strings
Take the string
'lstr = 'welcome to Beijing Museumitcpps fdsfs'
as an example, Introduces common operations on characters.
Check whether str is included in lstr, if so, return the starting index value, otherwise return -1.
Grammar:
lstr.find(str, start=0, end=len(lstr))
Example:
lstr = 'welcome to Beijing Museumitcpps fdsfs' print(lstr.find("Museum")) print(lstr.find("dada"))
operation result:
The same as the find() method, except that if str is not in lstr, an exception will be reported.
grammar:
lstr.index(str, start=0, end=len(lstr))
例:
lstr = 'welcome to Beijing Museumitcpps fdsfs' print(lstr.index("dada"))
运行结果:
返回 str在start和end之间 在 lstr里面出现的次数
语法:
lstr.count(str, start=0, end=len(lstr))
例:
lstr = 'welcome to Beijing Museumitcpps fdsfs' print(lstr.count("s"))
运行结果:
把 lstr 中的 str1 替换成 str2,如果 count 指定,则替换不超过 count 次.
1str.replace(str1, str2, 1str.count(str1))
例:
lstr = 'welcome to Beijing Museumitcpps fdsfs' print(lstr.replace("s", "ttennd"))
运行结果:
以 str 为分隔符切片 lstr,如果 maxsplit有指定值,则仅分隔 maxsplit 个子字符串
1str.split(str=" ", 2)
例:
lstr = 'welcome to Beijing Museumitcpps fdsfs' print(lstr.split("to", 5))
运行结果:
把字符串的第一个字符大写。
lstr.capitalize()
例:
lstr = 'welcome to Beijing Museumitcpps fdsfs' print(lstr.capitalize())
运行结果:
把字符串的每个单词首字母大写。
>>> a = "hello itcast" >>> a.title() 'Hello Itcast' #运行结果
检查字符串是否是以 obj 开头, 是则返回 True,否则返回 False
1str.startswith(obj)
例:
lstr = 'welcome to Beijing Museumitcpps fdsfs' print(lstr.startswith('we'))
运行结果:
检查字符串是否以obj结束,如果是返回True,否则返回 False.
1str.endswith(obj)
例:
lstr = 'welcome to Beijing Museumitcpps fdsfs' print(lstr.endswith('hfs'))
运行结果:
转换 lstr 中所有大写字符为小写
1str.lower()
例:
lstr = 'welcome to Beijing Museumitcpps fdsfs' print(lstr.lower())
运行结果:
转换 lstr 中的小写字母为大写
1str.upper()
例:
lstr = 'welcome to Beijing Museumitcpps fdsfs' print(lstr.upper())
运行结果:
删除lstr字符串两端的空白字符。
>>> a = "\n\t itcast \t\n" >>> a.strip() 'itcast' #运行结果
类似于 find()函数,不过是从右边开始查找。
1str.rfind(str, start=0,end=len(1str) )
例:
lstr = 'welcome to Beijing Museumitcpps fdsfs' print(lstr.rfind('eijing'))
运行结果:
类似于 index(),不过是从右边开始。
1str.rindex( str, start=0,end=len(1str))
例:
lstr = 'welcome to Beijing Museumitcpps fdsfs' print(lstr.rindex('eijing'))
运行结果:
把lstr以str分割成三部分,str前,str和str后。
1str.partition(str)
例:
lstr = 'welcome to Beijing Museumitcpps fdsfs' print(lstr.partition('eijing'))
运行结果:
mystr 中每个字符后面插入str,构造出一个新的字符串。
lstr = 'welcome to Beijing Museumitcpps fdsfs' str='233' lstr.join(str) li=["my","name","is","LY"] print(str.join(li))
运行结果:
本文详细的讲解了Python基础 ( 字符串 )。介绍了有关字符串,切片的操作。下标索引。以及在实际操作中会遇到的问题,提供了解决方案。希望可以帮助你更好的学习Python。
The above is the detailed content of Inventory of 16 common operations methods on Python strings. For more information, please follow other related articles on the PHP Chinese website!