字符串操作

s = 'abc123'

下面如未做特殊说明,均以s = 'abc123'做为例子

一、查询

1、如列表中切片操作,s[0],s[-1],s[1:3],s[:3]等

2、find

用法:S.find(sub[, start[, end]]) -> int,查找sub在字符串最开始出现的位置,没有返回-1,可以指定起始位置和结束位置,默认为整个字符串

s.find('bc')->1

同样功能还有rfind,查找sub在字符串最后出现的位置,没有返回-1,可以指定起始位置和结束位置,默认为整个字符串

如'abc123abc'.find('ab') ->0

'abc123abc'.rfind(ab') -> 6

3、index,rindex

用法同find,rfind,不过如果在字符串中没有找到sub,会报错(ValueError)

二、修改

1、replace

用法:S.replace(old, new[, count]) -> str

注意事项:这里不是真正替换原字符串,而是生成一个新的字符串返回。count:表示要替换的次数,不写默认把符合条件的都替换。

如:s.replace('bc','替换')  ->'a替换123'

如果s = 'abc123bc',s.replace('bc','替换',1) ->'a替换123bc'

2、capitalize

用法:S.capitalize() -> str,首字母大写,其余全小写

s.capitalize()-> 'Abc123'

3、title

用法:S.lower() -> str,首字母大写,其余全小写

与capitalize的区别:

'1abcD'.title() ->1Abcd

'1abcD'.capitalize() ->1abcd

4、lower

用法:S.lower() -> str,字母全部小写

5、upper

用法:S.upper() -> str,字母全部大写

6、lstrip

用法:S.lstrip([chars]) -> str,清除左边的空格符和

rstrip,strip用法同lstrip,分别为清除右边的空格符和清除两边的空格符

7、swapcase

用法:S.swapcase() -> str,字符串中大写变小写,小写变大写

'AbC aBc'.swapcase()->aBc AbC

四、增加

1、center

用法,S.center(width[, fillchar]) -> str,字符串居中。width表示长度,fillchar表示其余部分要以什么字符填充,默认空格

s.center(40,'/')->'/////////////////abc123/////////////////'

同样的操作还有ljust,rjust,用法与center一致,分别是左对齐和又对齐

2、zfill

用法:S.zfill(width) -> str,width长度,不够用0填充

'ab'.zfill(20)->000000000000000000ab

五、字符串判断

1、用法S.函数名(),返回True或者False

  isalnum:判断字符串是否都为数字和字母

  isalpha:判断字符串是否都为字母

  isdigit:判断字符串是否都为数字

  isdecimal:判断是否为十进制

  isidentifier:判断是否为合格的标识符(变量名)

  islower:判断字符串中字母是否都为小写

  isupper:判断字符串中字母是否都为大写

  istitle:判断字符串中单词(已空格区分)是否都首字母大写

  isspace:判断字符串是否为空格

2、endswith

用法:S.endswith(suffix[, start[, end]]) -> bool,判断字符串是否以suffix结尾,可以指定起始位置和结束位置,默认为整个字符串

如果s = 'abc123abbddcca'

s.endswith('cca') ->True

相同功能还有startswith,'abc123'.startswith('ab')-> True

 

  

六、其它

1、count

用法:S.count(sub[, start[, end]]) -> int,计算sub在字符串中出现的次数,可以指定起始位置和结束位置,默认为整个字符串。

如果s = 'abc123abbddcca'

s.count('a') ->3

s.count('a',0,7) ->2,类似于列表,顾头不顾尾

2、expandtabs

用法:S.expandtabs(tabsize=8) -> str,把tab( )用空格代替

如果s = 'abc 123'

s.expandtabs(20) -> abc                 123

3、format

用法:格式化输出

a = 'abc{s} 123'.format(s = '测试') ->abc测试 123

b = 'abc%s 123'%('测试')          ->abc测试 123

c = 'abc{0} 123 {1}'.format( '测试1','测试2') ->abc测试1 123 测试2

d = 'abc{s1}123'.format_map({'s1':'测试'}) ->abc测试123

推荐用前2种

4、join

用法:S.join(iterable) -> str

','.join(['1','2','3']) ->1,2,3

','.join('123') ->1,2,3

5、split

用法:S.split(sep=None, maxsplit=-1) -> list of strings,Return a list of the words in S

'abc,cba'.split(',') ->['abc', 'cba']

6、maketrans

用法:Return a translation table usable for str.translate().

p = str.maketrans("abcdefg","1234567")

print('abcdz'.translate(p)) ->1234z

类似于加密。解密

  

原文地址:https://www.cnblogs.com/zj-luxj/p/6814690.html