|
本章详细介绍了常用的29种字符串操作方法及代码示例。1.重复输出字符串print('x'*20)输出:xxxxxxxxxxxxxxxxxxxx2.通过索引获取字符串print('helloworld'[2:5])输出:llo3.in判断字符是否在字符串内print('e'in'helloworld')输出:True4.%格式化输出print('%sworld'%'hello')输出:helloworld5.+字符串拼接a='hello'b='world'c=a+bprint(c)输出:helloworld6.join拼接字符串a='hello'b='world'c=''.join([a,b])print(c)输出:helloworld7.count统计字符串中指定字母的出现次数a='www.baidu.com'print(a.count('w'))输出:38.center居中a="www.baidu.com"b=a.center(50,'*')print(b)输出:******************www.baidu.com*******************9.startswith判断字符串是否以指定字符串开头a='www.baidu.com'print(a.startswith('www'))输出:True10.find找制定字符出现的第一个位置a='www.baidu.com'b=a.find('u')print(b)输出:811.format格式化字符串 a='{0}.baidu.{1}'.format('www','com')print(a)#输出www.baidu.comstring='helloworld{xxx}{ppp}'b=string.format(xxx='xxx',ppp='ppp')print(b)#输出helloworldxxxpppc=string.format_map({'xxx':'xxx','ppp':'ppp'})print(c)#输出:helloworldxxxppp12.lower将字符串所有字符小写输出a='WangDaBai'print(a.lower())输出:wangdabai13.upper将字符串所有字符大写输出a='WangDaBai'print(a.upper())输出:WANGDaBAI14.strip去除掉字符串后的空格a='wangdabai'print(a.strip())#去除尾部空格输出:wangdabai15.repalce将指定字符替换为另一个指定字符a="wangdabai"b=a.replace('w','*')print(b)#输出:*angdabaic='wangdabai'.replace('d','xxxxxx',1)print(c)#输出wangxxxxxxabai16.split根据指定字符分割字符串a='wangdabai'.split() #默认以空格分割print(a) 输出:['wang','da','bai'] #以a分割a="wangdabai"b=a.split('a')print(b)输出:['wangd','b','i'] #从左侧以a分割1次a="wangdabai"b=a.split('a',1)print(b) 输出:['wangd','dabai'] #从右侧以a分割1次a="wangdabai"b=a.split('a',1)print(b) 输出:['wangda b','i'] 17.capitalize首字母大写string='helloworld'a=string.capitalize()print(a)输出:Helloworld 18.index返回位置a='helloworld'.index('w')print(a)输出:619.isalnum检测字符串是否由字母和数字组成a='12ssw'.isalnum()print(a) 输出:Truea='{'.isalnum()print(a) 输出:False20.isdecimal检测字符串内是否为十进制a='123456'.isdecimal()print(a) 输出:Truea='ws'.isdecimal()print(a)输出:False 21.isdigit判断是否为整形a='123456'.isdigit()print(a)#Truea='12325.2'.isdigit()print(a)#Falsea='ssdda'.isdigit()print(a)#False22.isidentifier()判断字符串是否以字母开头且合法 a='wangdabai'.isidentifier()print(a)#Truea='wangdabai123'.isidentifier()print(a)#Truea='123wangdabai'.isidentifier()print(a)#Falsea='wangdabai123!@#.isidentifier()print(a)#False23.islower判断是否为小写a='wangdabai'.islower()print(a)#Truea='Wangdabai'.islower()print(a)#False24.isupper判断是否为大写a='WANGDABAI'.isupper()print(a)#Truea='Wangdabai'.isupper()print(a)#False25.istitle判断是否为格式每个单词首字母大写a='WangDaBai'.istitle()print(a)#Truea='WangDabai'.istitle()print(a)#False26.ljust在字符串右侧加入字符a='sss'.ljust(50,'#')print(a)输出:sss###############################################27.rjust在字符串左侧加入字符a='sss'.rjust(50,'#')print(a)输出:###############################################sss28.swapcase大小写转换a='WangDaBai'.swapcase()print(a)输出:wANGdAbAI29.title将字符转转化为格式(首字母大写)a='wangdabai'.title()print(a)输出:WangDa Bai
|
|