python 中对于字符串的处理,也是相当厉害的
不仅支持传统编程语言中的双引号模式,也支持 shell 中的单引号模式,甚至还可以用三引号一次搞定多行字符串!
一对单引号的模式1
2
3
4
5
6
7
8'spam eggs'
'spam eggs'
'doesn\'t'
"doesn't"
'"Yes," he said.'
'"Yes,"he said.'
'"Isn\'t,"she said.'
'"Isn\'t,"she said.'
一对双引号的模式1
2
3
4
5
6
7
8
9
10"\"Yes,\"he said."
'"Yes," he said.'
"This is a rather long string containing\n\ hello =
... several lines of text just as you would do in C.\n\
... Note that whitespace at the beginning of the line is\
... significant."
print hello
This is a rather long string containing
several lines of text just as you would do in C.
Note that whitespace at the beginning of the line is significant.
一对三引号的模式1
2
3
4
5
6
7
8print """\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
"""
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
总结:
如果字符串中只包含单引号,不包含双引号,那就可以用一对双引号给包起来
如果字符串中之包含双引号,不包含单引号,那就可以用一对单引号给包起来
当需要使用多行的字符串时,可以使用一对三引号,被三引号给包起来的所有内容不进行转义,即所有转义字符无效
同时,还可以使用 “原始” 字符串,与三引号具有同样的效果,只需要在引号前面加个“r”1
2
3
4
5r"This is a rather long string containing\n\ hello =
... several lines of text much as you would do in C."
print(hello)
This is a rather long string containing\n\
several lines of text much as you would do in C.
字符串还可以任意拼接和重复1
2'<' + 'niko'*5 + '>'
'< niko niko niko niko niko >'
相邻的两个引号内的字符串即使不用加号也会自动拼接在一起,但在调用方法时不适用1
2
3
4
5
6
7
8
9'str' 'ing' # <- This is ok
'string'
'str'.strip() + 'ing' # <- This is ok
'string'
'str'.strip() 'ing' # <- This is invalid
File "<stdin>", line 1, in ?
'str'.strip() 'ing'
^
SyntaxError: invalid syntax
可以使用冒号来取任意长度的连续字符串1
2
3
4
5
6
7
8
9'str' 'ing' word =
4] # 取 4 word[
'n'
2:] #2 到最后 word[
'ring'
2] # 最前到 2 word[:
'st'
0:2] # 取 0-2 word[
'st'
python 字符串定义后为常量,不可任意修改其中的某个字符1
2
3
42] = 'k' word[
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
索引也可以为负值,即自右向左算1
2
3
4-2:] word[
'ng'
-2] word[:
'stri'
-0 其实就是 0,官方给出的示例索引表如下
1 | +---+---+---+---+---+ |
字符串求长度函数为 len()1
2
3'jreiouwtndouijfnbvioftretjk' s =
len(s)
27