主要内容
- 字符串的使用说明
除了数字,Python还可以操作字符串。
字符串: 由单引号(’…’)或双引号(”…”)括起来即为字符串。
转义引号:使用 \
操作
>>> 'spam eggs' # 单引号'spam eggs'>>> 'doesn\'t' # 使用 \ 对单引号进行转译"doesn't">>> "doesn't" # ...字符串中有单引号时 最外层使用双引号"doesn't">>> '"Yes," they said.' # 字符串中有双引号时 外层使用单引号'"Yes," they said.'>>> "\"Yes,\" they said." # 同时使用双引号时 \ 作为转译字符'"Yes," they said.'>>> '"Isn\'t," they said.' # 最外层使用单引号,内部使用双引号时不再转译'"Isn\'t," they said.'
字符串中的换行符使用 \n
>>> '"Isn\'t," they said.''"Isn\'t," they said.'>>> print('"Isn\'t," they said.')"Isn't," they said.>>> s = 'First line.\nSecond line.' # \n 回车 新换行>>> s # 不使用print() 函数 默认输出字符圆形'First line.\nSecond line.'>>> print(s) # 使用 print()打印, \n 将换行First line.Second line.
如果不希望将前缀为 \ 的字符解释为特殊字符,在第一个引号之前添加 r 来使用原始字符串:
>>> print('C:\some\name') # 这里 \n 会新换一行C:\someame>>> print(r'C:\some\name') # 添加 r 前缀C:\some\name
多行显示 使用 """....""" 或者 '''....''' 方式
>>> print("""\... 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
字符串之间使用 + 表示进行拼接,使用 * 后跟数字进行多次
>>> # 打印3次 'un', 后面连接 'ium'>>> 3 * 'un' + 'ium''unununium'
两个或多个字符串之间使用空格也可以进行连接
>>> 'Py' 'thon''Python'
当长字符串断开,使用 () 进行连接
>>> text = ('Put several strings within parentheses '... 'to have them joined together.')>>> text'Put several strings within parentheses to have them joined together.'
注意:使用空格连接字符串只能是 ‘xxx’ ‘xxxx’ 这种形式,如果用变量 ‘xxx’ 会报错。
>>> prefix = 'Py'>>> prefix 'thon' # 不能用变量空格连接字符串File "<stdin>", line 1prefix 'thon'^SyntaxError: invalid syntax>>> ('un' * 3) 'ium'File "<stdin>", line 1('un' * 3) 'ium'^SyntaxError: invalid syntax
字符串可以使用索引来访问其中的值,默认索引从0开始
>>> word = 'Python'>>> word[0] # 索引为0'P'>>> word[5] # 索引为5'n'
索引值使用负数,表示从后往前数
>>> word[-1] # 最后一个'n'>>> word[-2] # 倒数第二个'o'>>> word[-6]'P'
同样,也可以从字符串中切片取其中的部分字符
>>> word[0:2] # 从索引0(包含索引0)开始到索引2(不包含索引2)之间的字符'Py'>>> word[2:5] # 从索引2(包含索引2)开始到索引5(不包含索引5)之间的字符'tho'
s[:x] 表示从索引0开始到索引x之间的字符(不包含索引x)
s[x:] 表示从索引x开始到最后的字符(包含索引x)
>>> word[:2]'Py'>>> word[2:]'thon'>>> word[:2] + word[2:]'Python'>>> word[-2:] # 最后2位'on'
+---+---+---+---+---+---+| P | y | t | h | o | n |+---+---+---+---+---+---+0 1 2 3 4 5 6-6 -5 -4 -3 -2 -1
索引值超出文本长度会报错
>>> word[42] # word变量的长度只有6Traceback (most recent call last):File "<stdin>", line 1, in <module>IndexError: string index out of range
在对文本进行切片时超出长度时取值时如果超出长度返回’’
>>> word[4:42]'on'>>> word[42:]''
字符串一旦赋值,不能通过索引更改其中的字符,否则会报错。
>>> word[0] = 'J'Traceback (most recent call last):File "<stdin>", line 1, in <module>TypeError: 'str' object does not support item assignment>>> word[2:] = 'py'Traceback (most recent call last):File "<stdin>", line 1, in <module>TypeError: 'str' object does not support item assignment
使用 + 可以连接不同的字符创建新字符串
>>> 'J' + word[1:]'Jython'>>> word[:2] + 'py''Pypy'
使用 len() 函数可以获取字符串的长度。
>>> s = 'supercalifragilisticexpialidocious'>>> len(s)34
