美文网首页
字符串的处理方法

字符串的处理方法

作者: August________ | 来源:发表于2019-12-28 17:10 被阅读0次

字符串的处理方法

center

  • 通过在两边添加字符让字符串居中
>>> "The Middle by Jimmy Eat World".center(39)
'     The Middle by Jimmy Eat World     '
>>> "The Middle by Jimmy Eat World".center(39, "*")
'*****The Middle by Jimmy Eat World*****'

find

  • 在字符串中查找子串,如果找到,就返回子串的第一个字符的的索引,否则返回-1
>>> 'With a moo-moo here,and a moo-moo there'.find('moo')
7
>>> title = 'python is a language'
>>> title.find("is")
7
>>> title.find("python")
0
>>> title.find('abc')
-1

join

  • 用于合并序列的元素
>>> seq = ['1', '2', '3', '4', '5', '6']
>>> sep = '+'
>>> sep.join(seq)
'1+2+3+4+5+6'
>>> dirs = '', 'usr', 'bin', 'env'
>>> dirs
('', 'usr', 'bin', 'env')
>>> '/'.join(dirs)
'/usr/bin/env'
>>> print("C:" + '/'.join(dirs))
C:/usr/bin/env

lower

  • 返回字符串的小写版
>>> "Hello World".lower()
'hello world'

title

  • 将字符串转化成词首大写
>>> 'hello world'.title()
'Hello World'

replace

  • 指定子串来代替另一个字符串
>>> 'this is a test'.replace('is', 'eez')
'theez eez a test'

split

  • 与join相反,分离序列中的元素
>>> '1+2+3+4+5+6'.split("+")
['1', '2', '3', '4', '5', '6']
>>> '/usr/bin/env'.split("/")
['', 'usr', 'bin', 'env']

strip

  • 将字符串的开头和结尾的空白删除,并返回删除后的结果
>>> '      hello world           '.strip()
'hello world'

translate

  • 同时替换多个字符

  • 使用translate前必须创建一个转化表,这个转换表指出来不同的Unicode码点之间的转化关系,要创建转换表,可对字符串类型str调用方法makestrans。

  • 将字符串中c和s替换成k和z

>>> table = str.maketrans('cs', 'kz')
>>> table
{99: 107, 115: 122}
>>> 'this is an incredible test'.translate(table)
'thiz iz an inkredible tezt'

相关文章

网友评论

      本文标题:字符串的处理方法

      本文链接:https://www.haomeiwen.com/subject/eibsoctx.html