字符串
拼接
拼接 Python 字符串最简单的方法,就是采用字符串连接操作符 +:
>>> x = "Hello" + "World"
>>> x
'Hello World'
转义序列
转义序列 | 代表的字符 |
---|---|
\' | 单引号 |
\" | 双引号 |
\\ | 反斜杠 |
\a | 振铃符 |
\b | 退格符 |
\f | 换页符 |
\n | 换行符 |
\r | 回车符(与\n 不同) |
\t | 制表符( Tab) |
\v | 纵向制表符 |
方法
join
以字符串列表为参数,将字符串连在一起形成一个新字符串,各元素之间插入调用者字符串。
>>> " ".join(["join", "puts", "spaces", "between", "elements"])
'join puts spaces between elements'
>>> "::".join(["Separated", "with", "colons"])
'Separated::with::colons'
split
split 方法返回字符串中的子字符串列表。
>>> x = "You\t\t can have tabs\t\n \t and newlines \n\n " \
"mixed in"
>>> x.split()
['You', 'can', 'have', 'tabs', 'and', 'newlines', 'mixed', 'in']
>>> x = "Mississippi"
>>> x.split("ss")
['Mi', 'i', 'ippi']
info
默认情况下,split 方法将依据所有空白字符进行拆分,而不仅是一个空格符。但也可通过传入一个可选参数来基于特定的序列拆分。
字符串转数字
利用函数 int 和 float,可以将字符串分别转换为整数或浮点数。
>>> float('123.456')
123.456
>>> int('3333')
3333
caution
如果字符串无法转换为指定类型的数值,那么这两个函数将会引发 ValueError 异常。
去除多余的空白符
strip 函数将移除字符串首尾的空白字符。lstrip 和 rstrip 函数分别移除原字符串左边或右边的空白符。
>>> x = " Hello, World\t\t "
>>> x.strip()
'Hello, World'
>>> x.lstrip()
'Hello, World\t\t '
>>> x.rstrip()
' Hello, World'
info
在上述例子中,制表符也被当作是空白符。
strip、 rstrip 和 lstrip 方法可以附带一个参数,这个参数包含了需要移除的字符。
>>> x = "www.python.org"
>>> x.strip("w") # 删除所有的 w 字符
'.python.org'
>>> x.strip("gor") # 删除所有的 g、o、r 字符
'www.python.'
>>> x.strip(".gorw") # 删除所有的 g、o、r、w 字符
'python'
caution
注意,strip 方法会移除参数字符串中的所有字符,字符的顺序可随意。
format
format 方法用了两个参数,同时给出了包含被替换字段的格式字符串,以及替换后的值。
>>> "{0} is the {1} of {2}".format("Ambrosia", "food", "the gods")
'Ambrosia is the food of the gods'
>>> "{{Ambrosia}} is the {0} of {1}".format("food", "the gods")
'{Ambrosia} is the food of the gods
命名参数
>>> "{food} is the food of {user}".format(food="Ambrosia", user="the gods")
'Ambrosia is the food of the gods'