Python 字符串
除了数字,Python还可以操作字符串。字符串的形式是单引号('......')双引号(''.........'')或三个单引号('''..........''')
>>> 'spam and eggs '
'spam and eggs '
>>> 'doesn\'t'
"doesn't"
>>> 'py' + 'thon'
'python'
>>> word = 'pyhton'
>>> word[0]
'p'
>>> word[2]
'h'
>>> word[-1]
'n'
1、用 + 号合并字符串,2、字符串支持索引 word[1] ,3、字符串还支持负数索引 word[-1]
>>> word[0:2]
'py'
----------------------
p y t h o n
----------------------
0 1 2 3 4 5 6 (0-5是整数索引的位置 6 是字符串的长度)
-6 -5 -4 -3 -2 -1 (-1 到 -6是负数的索引位置)
1、Python也支持切片,索引可以提取单个字符,而切片却可以提取多个字符,注意输出结果包括切片开始,但不包括切片结束。
>>> word[0] = 'x'
Traceback (most recent call last):
File "", line 1, in
TypeError: 'str' object does not support item assignment
>>> a = 'abcdefghijklmnopqrstuvwxyz'
>>> len(a)
26
2、Python字符串不能修改,只能从新定义。3、函数 len() 返回值是字符串的长度。