Python中,字符串是用引号括起来的一串字符,单引号(‘abc’)和双引号(“abc”)都是表示字符串。
1、split() ------字符串分割
定义:
S.split(sep=None, maxsplit=-1) -> list of strings
使用方法:
split()方法是以指定的字符为分割符,将字符串分割成多个元素,并保存在一个列表中(返回一个列表)。
如果不传参数,则默认以空格(‘ ’)为分割,同时可以将字符串两端的空格去掉:
>>> string = " ab cd ef gh "
>>> lst = string.split()
>>> lst
['ab', 'cd', 'ef', 'gh']
如果指定分割符,则以指定符号分割;如果指定了最大分割数maxsplit,则按maxsplit分割相应次数。
>>> string = "ab|cd|ef|gh"
>>> string.split('|')
['ab', 'cd', 'ef', 'gh']
>>> string.split('|', maxsplit=2)
['ab', 'cd', 'ef|gh']
2、format() ------字符串格式化
定义:
S.format(*args, **kwargs) -> str
使用方法:
# 不设置指定位置,按默认顺序
>>> "{} {}".format("hello", "world")
'hello world'
# 设置指定位置
>>> "{0} {1}".format("hello", "world")
'hello world'
# 设置指定位置
>>> "{1} {0} {1}".format("hello", "world")
'world hello world'
如果在字符串中需要直接展示花括号,则用另一个花括号包裹起来转义。
>>> "{{我是谁}}:{}".format("皮卡丘")
'{我是谁}:皮卡丘'
也支持参数式填写:
>>> "我是谁:{pikachu}".format(pikachu="皮卡丘")
'我是谁:皮卡丘'
数字格式化:
#数字格式化
>>> "{:.2f}".format(3.1415926)
'3.14'
3、join() ------将可迭代对象转化为字符串
定义:
S.join(iterable) -> str
使用方法:
‘seq’.join(obj)
seq:为分隔符,可以为空;
obj: 一个可迭代对象,可以为列表,元祖,字典等。
>>> a = ["hello", "world", "!"]
>>> ' '.join(a)
'hello world !'
字典也可以转化为字符串。如果不写.values(),默认是将键拼接。
>>> b = {'a':'hello', 'b':'world'}
>>> ' '.join(b.values())
'hello world'
4、center() ------字符串居中
定义:
返回一个长度为width,两边用fillchar(单字符)填充的字符串,即字符串str居中,两边用fillchar填充。若字符串的长度大于width,则直接返回字符串str。
fillchar的默认字符为空格。
def center(self, width, fillchar=None): -> str
使用方法:
>>> a = 'hello'
>>> a.center(20,'*')
'*******hello********'
若字符串长度大于width,则返回原字符串。
>>> a = 'hello world!'
>>> a.center(10,'*')
'hello world!