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

Python字符串必备的31个方法,推荐收藏!

时间:2023-03-13 12:49:59 科技观察

string是Python中的基本数据类型,几乎每一个Python程序都会用到它。1.Slicings切片,根据一定的条件(比如特定的范围,索引,分割值)从列表或元组中提取一些元素s='hello's=s[:]print(s)#hellos='hello's=s[3:8]print(s)#hello2,strip()strip()方法用于去除字符串首尾的指定字符(默认为空格或换行符)或字符序列。s='hello'.strip()print(s)#hellos='###hello###'.strip()print(s)####hello###使用strip()方法时,default删除空格或换行符,因此不会删除#符号。您可以将指定的字符添加到strip()方法中,如下所示。s='###hello###'.strip('#')print(s)#hello另外,当指定的内容不在首尾时,不会被移除。s='\n\thello\n'.strip('\n')print(s)##hello='\n\thello\n'.strip('\n')print(s)#hello第一个\n之前有一个空格,所以只取末尾的换行符。最后,strip()方法的参数是剥离其值的所有组合,可以在下面的案例中看到。s='www.baidu.com'.strip('cmow.')print(s)#baidu最外层的第一个和最后一个字符将从字符串中剥离。从前面删除字符,直到到达字符集中不包含的字符串字符。类似的动作也发生在尾部。3.lstrip()去除字符串左侧的指定字符(默认为空格或换行符)或字符序列。s='hello'.lstrip()print(s)#hello同理,左边字符集包含的所有字符串都可以去掉。s='Arthur:three!'.lstrip('Arthur:')print(s)#ee!4.rstrip()去除字符串右侧的指定字符(默认为空格或换行符)或字符序列。s='hello'.rstrip()print(s)#hello5,removeprefix()Python3.9去除前缀的函数。#python3.9s='Arthur:three!'.removeprefix('Arthur:')print(s)#three!与strip()相比,它并没有将字符集中的字符串一一匹配。6.removesuffix()函数去除Python3.9的后缀。s='HelloPython'.removesuffix('Python')print(s)#Hello7,replace()将字符串中的内容替换为指定的内容。s='python中的字符串方法'.replace('','-')print(s)#string-methods-in-pythons='python中的字符串方法'.replace('','')print(s)#stringmethods在python8中,re.sub()是正则表达式,sub是substitute表示替换。re.sub是一个相对复杂的替换。importres="python中的字符串方法"s2=s.replace('','-')print(s2)#string----methods-in-pythons="python中的字符串方法"s2=re.sub("\s+","-",s)print(s2)#string-methods-in-python与replace()相比,使用re.sub()替换确实更高级。9.split()分离字符串,最终结果是一个列表。s='stringmethodsinpython'.split()print(s)#['string','methods','in','python']不指定分隔符时,默认以空格分隔。s='stringmethodsinpython'.split(',')print(s)#['stringmethodsinpython']此外,还可以指定字符串的拆分次数。s='stringmethodsinpython'.split('',maxsplit=1)print(s)#['string','methodsinpython']10.rsplit()开始将字符串从右边分开。s='python中的字符串方法'.rsplit('',maxsplit=1)print(s)#['python中的字符串方法','python']11,join()string.join(seq).将seq中的所有元素(字符串表示)合并为一个新的字符串,以string为分隔符。list_of_strings=['string','methods','in','python']s='-'.join(list_of_strings)print(s)#string-methods-in-pythonlist_of_strings=['string','methods','in','python']s=''.join(list_of_strings)print(s)#python12中的字符串方法,upper()将字符串中的所有字母转为大写。s='simpleisbetterthancomplex'.upper()print(s)#SIMPLEISBETTERTHANCOMPLEX13,lower()将字符串中的所有字母转换为小写。s='SIMPLEISBETTERTHANCOMPLEX'.lower()print(s)#simpleisbetterthancomplex14,capitalize()将字符串中的第一个字母转换为大写。s='simpleisbetterthancomplex'.capitalize()print(s)#Simpleisbetterthancomplex15,islower()判断字符串中的字母是否全部为小写,是则返回True,否则返回False。print('SIMPLEISBETTERTHANCOMPLEX'.islower())#Falseprint('simpleisbetterthancomplex'.islower())#True16,isupper()判断字符串中的字母是否全部大写,如果是则返回True,否则返回False。print('SIMPLEISBETTERTHANCOMPLEX'.isupper())#Trueprint('SIMPLEISBETTERTHANcomplex'.isupper())#False17,isalpha()如果字符串至少有一个字符并且所有字符都是字母,那么返回True,否则返回False。s='python'print(s.isalpha())#Trues='123'print(s.isalpha())#Falses='python123'print(s.isalpha())#Falses='python-123'print(s.isalpha())#False18,isnumeric()如果字符串只包含数字字符则返回True,否则返回False。s='python'print(s.isnumeric())#Falses='123'print(s.isnumeric())#Trues='python123'print(s.isnumeric())#Falses='python-123'print(s.isnumeric())#False19,isalnum()如果字符串中至少有一个字符且所有字符都是字母或数字则返回True,否则返回False。s='python'print(s.isalnum())#Trues='123'print(s.isalnum())#Trues='python123'print(s.isalnum())#Trues='python-123'print(s.isalnum())#false20,count()返回指定内容在字符串中出现的次数。n='helloworld'.count('o')print(n)#2n='helloworld'.count('oo')print(n)#021、find()检测指定内容是否包含在string,如果返回起始索引值,否则返回-1。s='机器学习'idx=s.find('a')print(idx)print(s[idx:])#1#machineLearnings='机器学习'idx=s.find('aa')print(idx)print(s[idx:])#-1#g另外还可以指定起始范围。s='MachineLearning'idx=s.find('a',2)print(idx)print(s[idx:])#10#warning22,rfind()类似于find()函数,返回的是最后一次出现的字符串,如果没有匹配则为-1。s='MachineLearning'idx=s.rfind('a')print(idx)print(s[idx:])#10#warning23,startswith()检查字符串是否以指定内容开头,如果是则返回True它是,否则返回False。print('Patrick'.startswith('P'))#True24,endswith()检测字符串是否以指定内容结尾,是则返回True,否则返回False。print('Patrick'.endswith('ck'))#True25,partition()string.partition(str),有点像find()和split()的组合。从str出现的第一个位置开始,将字符串string分成3元元组(string_pre_str,str,string_post_str),如果string不包含str则string_pre_str==string。s='Python很棒!parts=s.partition('is')print(parts)#('Python','is','awesome!')s='Pythonisawesome!'parts=s.partition('was')print(parts)#('Pythonisawesome!','','')26.center()返回一个新字符串,其中原始字符串居中并用空格填充到长度宽度。s='Pythonisawesome!'=s.center(30,'-')print(s)#------Pythonisawesome!-----27,ljust()返回一个原始字符字符串左对齐并用空格填充为长度宽度的新字符串。s='Pythonisawesome!'s=s.ljust(30,'-')print(s)#Pythonisawesome!------------28,rjust()返回一个原始字符字符串右对齐并用空格填充为长度宽度的新字符串。s='Python真棒!'=s.rjust(30,'-')print(s)#--------------Python真棒!29、f-Stringsf-string是格式定界字符串的新语法。与其他格式化方法相比,它们不仅更易读、更简洁、更不容易出错,而且速度更快!num=1language='Python's=f'{language}是编程中的第{num}位!'print(s)#Python是编程中的第1位!num=1language='Python's=f'{language}是编程中的数字{num*8}!'print(s)#Python是编程中的数字8!30、swapcase()翻转字符串中字母的大小写。s='HELLOworld's=s.swapcase()print(s)#helloWORLD31,zfill()字符串。填充(宽度)。返回长度为宽度的字符串。原始字符串右对齐并用0填充。s='42'.zfill(5)print(s)#00042s='-42'.zfill(5)print(s)#-0042s='+42'.zfill(5)print(s)#+0042