笔记:字符串的基本操作

字符串的基本操作

设置字符串的格式

>>> format = 'Hello, %s, %s enough for ya?'
>>> value = ('World', 'Hot')
>>> format % value
'Hello, World, Hot enough for ya?'

>>> "{}, {} and {}".format("first", "second", "third")
'first, second and third'
# 替换字段没有名称
>>> "{3} {0} {2} {1} {3} {0}".format("be", "not", "or", "to")
'to be or not to be'
# 索引作为替换字段名称
>>> from math import pi
>>> '{name} is approximately {value:.2f}.'.format(value=pi, name='π')
'π is approximately 3.14.'
# 通过命名字段

%s被称为转换说明符,指出了要将值插入到什么地方。s意味着将值视为字符串进行格式设置。如果指定的值不是字符串,将使用str将其转换为字符串。

字符串方法

center

方法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

方法find在字符串中查找子串。如果找到,就返回子串的第一个字符的索引,否则返回-1。

>>> 'The Middle by Jimmy Eat World'.find('Eat')
20
>>> title = 'The Middle by Jimmy Eat World'
>>> title.find('The')
0
>>> title.find('by')
11
>>> title.find('one')
-1
>>> 

join

与split相反,用于合并序列的元素。

>>> seq = ['1', '2', '3', '4', '5']
>>> sep = '+'
>>> sep.join(seq)
'1+2+3+4+5'

>>> dirs = '', 'usr', 'bin', 'env'
>>> '/'.join(dirs)
'/usr/bin/env'
>>> print('C:' + '\\'.join(dirs))
C:\usr\bin\env
>>> 

>>> seq = [1, 2, 3, 4, 5]
>>> sep = '+'
>>> sep.join(seq)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected str instance, int found

# join所合并的序列元素,必须全都是字符串

lower

返回字符串的小写版本

>>> 'hEllO, wOrld'.lower()
'hello, world'

>>> name = 'ZHANGSAN'
>>> names = ['zhangsan', 'lisi', 'wangerhu']
>>> if name.lower() in names: print('found it!')
... 
found it!
>>> 

replace

方法replace将指定子串都替换为另一个字符串,并返回替换后的结果。

>>> 'this is a pig'.replace('pig', 'dog')
'this is a dog'
>>> 

split

与join相反,用于将字符串拆分为序列,返回一个数组。

>>> '1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']
>>> '/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']

strip

将字符串开头和末尾的空白(但不包括中间的空白)删除,并返回删除后的结果。

>>> '         test        '.strip()
'test'
# 指定删除字符
>>> '********test**********'.strip('*')
'test'
posted @ 2019-08-22 15:15  大胡子哥dhzg  Views(115)  Comments(0)    收藏  举报