当前位置: 首页 > 科技观察

盘点Python字符串的16种常用操作

时间:2023-03-18 14:11:36 科技观察

大家好,我是Go进阶用户。上一篇文章给大家介绍了Python字符串。今天给大家分享一些Python字符串的常用操作。一起来看看吧~1.常用操作以字符串'lstr='welcometoBeijingMuseumitcppsfdsfs'为例,介绍字符的常用操作。<1>find检测str是否包含在lstr中,如果返回起始索引值,否则返回-1。语法:lstr.find(str,start=0,end=len(lstr))例子:lstr='welcometoBeijingMuseumitcppsfdsfs'print(lstr.find("博物馆"))print(lstr.find("dada"))运行结果:<2>index和find()方法一样,只是如果str不在lstr中,会报异常。语法:lstr.index(str,start=0,end=len(lstr))例子:lstr='welcometoBeijingMuseumitcppsfdsfs'print(lstr.index("dada"))运行结果:<3>countreturnsstratstartandend语法:lstr.count(str,start=0,end=len(lstr))示例:lstr='welcometoBeijingMuseumitcppsfdsfs'print(lstr.count("s"))运行结果:<4>replace将lstr中的str1替换为str2.如果指定count,则替换不会超过count次。1str.replace(str1,str2,1str.count(str1))例子:lstr='welcometoBeijingMuseumitcppsfdsfs'print(lstr.replace("s","ttennd"))运行结果:<5>split以str为分隔符slicelstr,如果maxsplit有指定值,则只分割maxsplit子串1str.split(str="",2)例子:lstr='welcometoBeijingMuseumitcppsfdsfs'print(lstr.split("to",5))运行结果:<6>capitalize将字符串的第一个字符大写。lstr.capitalize()示例:lstr='welcometoBeijingMuseumitcppsfdsfs'print(lstr.capitalize())运行结果:<7>标题将字符串中每个单词的首字母大写。>>>a="helloitcast">>>a.title()'HelloItcast'#Runresult<8>startswith检测字符串是否以obj开头,是则返回True,否则返回False1str.startswith(obj)示例:lstr='welcometoBeijingMuseumitcppsfdsfs'print(lstr.startswith('we'))运行结果:<9>endswith检查字符串是否以obj结尾,如果返回True,否则返回False。1str.endswith(obj)例子:lstr='welcometoBeijingMuseumitcppsfdsfs'print(lstr.endswith('hfs'))运行结果:<10>lower将lstr中的所有大写字符转换为小写1str.lower()例子:lstr='welcometoBeijingMuseumitcppsfdsfs'print(lstr.lower())runResult:<11>upper将lstr中的小写字母转换为大写1str.upper()例子:lstr='welcometoBeijingMuseumitcppsfdsfs'print(lstr.upper())runningresult:<12>strip删除lstr字符串两端的空白字符。>>>a="\n\titcast\t\n">>>a.strip()'itcast'#Runresult<13>rfind类似于find()函数,但是从右边开始查找。1str.rfind(str,start=0,end=len(1str))例子:lstr='welcometoBeijingMuseumitcppsfdsfs'print(lstr.rfind('eijing'))运行结果:<14>rindex类似于index(),但是右边是Start。1str.rindex(str,start=0,end=len(1str))例子:lstr='welcometoBeijingMuseumitcppsfdsfs'print(lstr.rindex('eijing'))运行结果:<15>partition将lstr用str分成三部分,在str之前,在str和str之后。1str.partition(str)例子:lstr='welcometoBeijingMuseumitcppsfdsfs'print(lstr.partition('eijing'))运行结果:<16>在joinmystr中的每个字符后面插入str,构造一个新的字符串。lstr='welcometoBeijingMuseumitcppsfdsfs'str='233'lstr.join(str)li=["my","name","is","LY"]print(str.join(li))results:2.总结这个文章详细解释了Python(字符串)的基础知识。介绍对字符串和切片的操作。下标索引。以及在实际操作中遇到的问题,都给出了解决方案。希望能帮助大家更好的学习Python。