>>> from env_helper import info; info()
页面更新时间: 2024-01-14 09:32:35
运行环境:
    Linux发行版本: Debian GNU/Linux 12 (bookworm)
    操作系统内核: Linux-6.1.0-16-amd64-x86_64-with-glibc2.36
    Python版本: 3.11.2

6.1. 字符串操作

文本是最常见的数据形式,它也是Python中最常用的数据类型。我们可以使用引号( '" )来创建字符串。

Python的字符串操作非常灵活,我们可以用 + 操作符连接两个字符串, 可以从字符串中提取部分字符串,添加或删除空白字符,将字母转换成小写或大写,还可以检查字符串的格式是否正确。 你甚至可以编写 Python 代码访问剪贴板,复制或粘贴文本,将枯燥的文本格式化工作自动化。

让我们来看看, Python 提供的写入、打印和访问字符串的有哪些方法。

6.1.1. 字符串字面量

创建字符串很简单,只要为变量分配一个值即可。例如:

>>> var1 = 'Hello World!'
>>> var2 = "Python Osgeo"

在Python中输入字符串值相当简单的: 它们以单引号开始和结束。 但是如何才能在字符串内使用单引号呢? 输入 'That is Alice's cat.' 是不行的, 因为Python认为这个字符串在 Alice 之后就结束了, 剩下的( s cat.')是无效的Python代码。 好在,有几种方法来输入字符串。

字符串可以用双引号开始和结束,就像用单引号一样。 使用双引号的一个好处,就是字符串中可以使用单引号字符。 在交互式环境中输入以下代码:

>>> spam = "That is Alice's cat."

因为字符串以双引号开始,所以Python知道单引号是字符串的一部分, 而不是表示字符串的结束。但是, 如果在字符串中既需要使用单引号又需要使用双引号, 那就要使用转义字符。

6.1.2. 转义字符

“转义字符”让你输入一些字符,它们用其他方式是不可能放在字符串里的。 转义字符包含一个倒斜杠(),紧跟着是想要添加到字符串中的字符。 (尽管它包含两个字符,但大家公认它是一个转义字符。) 例如,单引号的转义字符是\’ 。你可以在单引号开始和 结束的字符串中使用它。为了看看转义字符的效果, 在交互式环境中输入以下代码:

>>> spam = 'Say hi to Bob\'s mother.'

Python知道,因为 Bob\'s 中的单引号有一个倒斜杠, 所以它不是表示字符串结束的单引号。 转义字符 \'\" 让你能在字符串中加入单引号和双引号。

表6-1列出了可用的转义字符。

    <td style="border-color:#bfbfbf;vertical-align:top;width:207.4pt;">
    <p style="margin-left:0cm;"><strong>打印</strong></p>
    </td>
</tr><tr><td style="border-color:#bfbfbf;width:207.4pt;">
    <p style="margin-left:0cm;"><strong>\’</strong></p>
    </td>
    <td style="width:207.4pt;">
    <p style="margin-left:0cm;">单引号</p>
    </td>
</tr><tr><td style="border-color:#bfbfbf;vertical-align:top;width:207.4pt;">
    <p style="margin-left:0cm;"><strong>\”</strong></p>
    </td>
    <td style="vertical-align:top;width:207.4pt;">
    <p style="margin-left:0cm;">双引号</p>
    </td>
</tr><tr><td style="border-color:#bfbfbf;width:207.4pt;">
    <p style="margin-left:0cm;"><strong>\t</strong></p>
    </td>
    <td style="width:207.4pt;">
    <p style="margin-left:0cm;">制表符</p>
    </td>
</tr><tr><td style="border-color:#bfbfbf;vertical-align:top;width:207.4pt;">
    <p style="margin-left:0cm;"><strong>\n</strong></p>
    </td>
    <td style="vertical-align:top;width:207.4pt;">
    <p style="margin-left:0cm;">换行符</p>
    </td>
</tr><tr><td style="border-color:#bfbfbf;width:207.4pt;">
    <p style="margin-left:0cm;"><strong>\\</strong></p>
    </td>
    <td style="width:207.4pt;">
    <p style="margin-left:0cm;">倒斜杠</p>
    </td>
</tr></tbody></table>

表6-1转义字符

在交互式环境中输入以下代码:

>>> print("Hello there!\nHow are you?\nI'm doing fine.")
Hello there!
How are you?
I'm doing fine.

6.1.3. 原始字符串

可以在字符串开始的引号之前加上n使它成为原始字符串。 “原始字符串”完全忽略所有的转义字符, 打印出字符串中所有的倒斜杠。例如, 在交互式环境中输入以下代码:

>>> print(r'That is Carol\'s cat.')
That is Carol's cat.

因为这是原始字符串,Python认为倒斜杠是字符串的一部分, 而不是转义字符的开始。如果输入的字符串包含许多倒斜杠, 比如下一章中要介绍的正则表达式字符串,那么原始字符串就很有用。

6.1.4. 用三重引号的多行字符串

虽然可以用 \n 转义字符将换行放入一个字符串, 但使用多行字符串通常更容易。在Python中, 多行字符串的起止是3个单引号或3个双引号。 “三重引号”之间的所有引号、制表符或换行, 都被认为是字符串的一部分。Python的代码块缩进规则不适用于多行字符串。

打开文件编辑器,输入以下代码:

>>> print('''Dear Alice,
>>>
>>> Eve's cat has been arrested for catnapping, cat burglary, and extortion.
>>>
>>> Sincerely,
>>> Bob''')
Dear Alice,

Eve's cat has been arrested for catnapping, cat burglary, and extortion.

Sincerely,
Bob

将该程序保存为 catnapping.py 并运行。

请注意, Eve's 中的单引号字符不需要转义。 在原始字符串中,转义单引号和双引号是可选的。 下面的 print() 调用将打印出同样的文本, 但没有使用多行字符串:

>>> print('Dear Alice,\n\nEve\'s cat has been arrested for catnapping, cat burglary, and extortion.\n\nSincerely,\nBob')
Dear Alice,

Eve's cat has been arrested for catnapping, cat burglary, and extortion.

Sincerely,
Bob

6.1.5. 多行注释

虽然井号字符(#)表示这一行是注释,但多行字符串常常用作多行注释。 下面是完全有效的 Python 代码:

>>> """This is a test Python program.
>>> Written by Al Sweigart al@inventwithpython.com
>>> This program was designed for Python 3, not Python 2.
>>> """
>>> def spam():
>>>     """This is a multiline comment to help
>>>     explain what the spam() function does."""
>>>     print('Hello!')

6.1.6. 字符串下标和切片

字符串像列表一样,使用下标和切片。 可以将字符串 'Hello world!' 看成是一个列表, 字符串中的每个字符都是一个表项,有对应的下标。

' H e l l o w o r l d  !  '
0 1 2 3 4 5 6 7 8 9 10 11

字符计数包含了空格和感叹号, 所以 'Hello world!'有12个字符, H 的下标是0, !的下标是11。 在交互式环境中输入以下代码:

>>> spam = 'Hello world!'
>>> spam[0]
'H'
>>> spam[4]
'o'
>>> spam[-1]
'!'
>>> spam[0:5]
'Hello'
>>> spam[:5]
'Hello'
>>> spam[6:]
'world!'

如果指定一个下标,你将得到字符串在该处的字符。 如果用一个下标和另一个下标指定一个范围, 开始下标将被包含,结束下标则不包含。因此, 如果 spam'Hello world!'spam[0:5] 就是'Hello' 。 通过 spam[0:5] 得到的子字符串, 将包含 spam[0]spam[4] 的全部内容, 而不包括下标5处的空格。

请注意,字符串切片并没有修改原来的字符串。 可以从一个变量中获取切片,记录在另一个变量中。 在交互式环境中输入以下代码:

>>> spam = 'Hello world!'
>>> fizz = spam[0:5]
>>> fizz
'Hello'

通过切片并将结果子字符串保存在另一个变量中, 就可以同时拥有完整的字符串和子字符串, 便于快速简单的访问。

6.1.7. 字符串的 innot in 操作符

像列表一样, innot in 操作符也可以用于字符串。 用 innot in 连接两个字符串得到的表达式, 将求值为布尔值 TrueFalse 。 在交互式环境中输入以下代码:

>>> 'Hello' in 'Hello World'
True
>>> 'Hello' in 'Hello'
True
>>> '' in 'spam'
True
>>> 'HELLO' in 'Hello World'
False
>>> 'cats' not in 'cats and dogs'
False

这些表达式测试第一个字符串(精确匹配,区分大小写)是否在第二个字符串中。

By Bu Kun
© Copyright From 2020. Build on 2024-1-15. by BU Kun @ OSGeo China Chapter.

转义字符