python文本

文本

除了数字 Python 还可以操作文本(由 str 类型表示,称为“字符串”)。 这包括字符 "!", 单词 "rabbit", 名称 "Paris", 句子 "Got your back." 等等. "Yay! :)"。 它们可以用成对的单引号 ('...') 或双引号 ("...") 来标示,结果完全相同 2

>>>

>>> 'spam eggs'  # single quotes
'spam eggs'
>>> "Paris rabbit got your back :)! Yay!"  # double quotes
'Paris rabbit got your back :)! Yay!'
>>> '1975'  # digits and numerals enclosed in quotes are also strings
'1975'

要标示引号本身,我们需要对它进行“转义”,即在前面加一个 \。 或者,我们也可以使用不同类型的引号:

>>>

>>> 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
>>> "doesn't"  # ...or use double quotes instead
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'

在 Python shell 中,字符串定义和输出字符串看起来可能不同。 print() 函数会略去标示用的引号,并打印经过转义的特殊字符,产生更为易读的输出:

>>>

>>> s = 'First line.\nSecond line.'  # \n means newline
>>> s  # without print(), special characters are included in the string
'First line.\nSecond line.'
>>> print(s)  # with print(), special characters are interpreted, so \n produces new line
First line.
Second line.

如果不希望前置 \ 的字符转义成特殊字符,可以使用 原始字符串,在引号前添加 r 即可:

>>>

>>> print('C:\some\name')  # here \n means newline!
C:\some
ame
>>> print(r'C:\some\name')  # note the r before the quote
C:\some\name

原始字符串还有一个微妙的限制:一个原始字符串不能以奇数个 \ 字符结束;请参阅 此 FAQ 条目 了解更多信息及绕过的办法。

字符串字面值可以包含多行。 一种实现方式是使用三重引号:"""...""" 或 '''...'''。 字符串中将自动包括行结束符,但也可以在换行的地方添加一个 \ 来避免此情况。 参见以下示例:

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 times 'un', followed by '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.'

这项功能只能用于两个字面值,不能用于变量或表达式:

>>>

>>> prefix = 'Py'
>>> prefix 'thon'  # can't concatenate a variable and a string literal
  File "<stdin>", line 1
    prefix 'thon'
           ^^^^^^
SyntaxError: invalid syntax
>>> ('un' * 3) 'ium'
  File "<stdin>", line 1
    ('un' * 3) 'ium'
               ^^^^^
SyntaxError: invalid syntax

合并多个变量,或合并变量与字面值,要用 +

>>>

>>> prefix + 'thon'
'Python'

字符串支持 索引 (下标访问),第一个字符的索引是 0。单字符没有专用的类型,就是长度为一的字符串:

>>>

>>> word = 'Python'
>>> word[0]  # character in position 0
'P'
>>> word[5]  # character in position 5
'n'

索引还支持负数,用负数索引时,从右边开始计数:

>>>

>>> word[-1]  # last character
'n'
>>> word[-2]  # second-last character
'o'
>>> word[-6]
'P'

注意,-0 和 0 一样,因此,负数索引从 -1 开始。

除了索引操作,还支持 切片。 索引用来获取单个字符,而 切片 允许你获取子字符串:

>>>

>>> word[0:2]  # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5]  # characters from position 2 (included) to 5 (excluded)
'tho'

切片索引的默认值很有用;省略开始索引时,默认值为 0,省略结束索引时,默认为到字符串的结尾:

>>>

>>> word[:2]   # character from the beginning to position 2 (excluded)
'Py'
>>> word[4:]   # characters from position 4 (included) to the end
'on'
>>> word[-2:]  # characters from the second-last (included) to the end
'on'

注意,输出结果包含切片开始,但不包含切片结束。因此,s[:i] + s[i:] 总是等于 s

>>>

>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'

还可以这样理解切片,索引指向的是字符 之间 ,第一个字符的左侧标为 0,最后一个字符的右侧标为 n ,n 是字符串长度。例如:

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1

第一行数字是字符串中索引 0...6 的位置,第二行数字是对应的负数索引位置。i 到 j 的切片由 i 和 j 之间所有对应的字符组成。

对于使用非负索引的切片,如果两个索引都不越界,切片长度就是起止索引之差。例如, word[1:3] 的长度是 2。

索引越界会报错:

>>>

>>> word[42]  # the word only has 6 characters
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

但是,切片会自动处理越界索引:

>>>

>>> word[4:42]
'on'
>>> word[42:]
''

Python 字符串不能修改,是 immutable 的。因此,为字符串中某个索引位置赋值会报错:

>>>

>>> 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

参见

文本序列类型 --- str

字符串是 序列类型 ,支持序列类型的各种操作。

字符串的方法

字符串支持很多变形与查找方法。

格式字符串字面值

内嵌表达式的字符串字面值。

格式字符串语法

使用 str.format() 格式化字符串。

printf 风格的字符串格式化

这里详述了用 % 运算符格式化字符串的操作。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

知识的宝藏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值