字符串基本知识

已完成

除了数字,Python 还可操作字符串。 可用单引号 (') 或双引号 (") 将字符串括起,结果是一样的。 使用反斜杠 (\) 转义要在字符串本身中使用的引号。 下面是一个使用单引号的示例。

'spam eggs'  # Use single quotation marks.

输出为:

'spam eggs'

本示例使用反斜杠:

'doesn\'t'  # Use backslash \' to escape the single quotation mark or apostrophe.

输出为:

"doesn't"

本示例将撇号括在双引号中:

"doesn't"  # Use double quotation marks to enclose the entire string.

输出为:

"doesn't"

在 Python 的交互式解释器和 Visual Studio Code 中的 Jupyter Notebook 中,输出字符串用引号括起来,并使用反斜杠转义特殊字符。 尽管此输出有时看起来与输入不同(闭合引号可能会更改),但两个字符串是等效的。 如果字符串包含单个引号且没有双引号,该字符串将用双引号括起来。 否则,将其括在单引号内。

print() 函数通过省略封闭引号和打印转义的特殊字符来生成更具可读性输出。 下面这个示例没有 print()

'"Isn\'t," she said.'

输出为:

'"Isn\'t," she said.'

下面是另一个使用 print() 的示例:

print('"Isn\'t," she said.')

输出为:

"Isn't," she said.

如果不希望将转义字符(以反斜杠开头)解释为特殊字符,请通过在第一个引号前面添加“r”来使用原始字符串。 首先,下面这个示例没有“r”:

print('C:\some\name')  # Here, the slash before the "n" (\n) means newline!

输出为:

C:\some
ame

以下示例使用“r”:

print(r'C:\some\name')  # Note the "r" before the single quotation mark.

输出为:

C:\some\name

字符串文本

字符串文本可跨越多行,由三引号 (""") 或 (''') 分隔。

由于 Python 不提供创建多行注释的方法,因此开发人员通常仅为此目的使用三引号。 但在 Jupyter Notebook 中,此类引号定义显示为代码单元输出的字符串文本:

"""
Everything between the sets of three quotation marks, including new lines,
is part of the multiline comment. Technically, the Python interpreter
sees the comment as simply a string. And, because the string is not otherwise
used in code, it's ignored.
"""

输出为:

"\nEverything between the sets of three quotation marks, including new lines,\nis part of the multiline comment. Technically, the Python interpreter\nsees the comment as simply a string. And, because the string is not otherwise\nused in code, it's ignored.\n"

因此,最好在笔记本中每行的开头使用哈希 (#) 注释字符。 更好的做法是,只在 Jupyter Notebook 中的代码单元外使用 Markdown 单元!

可使用加号运算符 (+) 将字符串串联(粘合在一起),并使用乘法运算符 (*) 进行重复:

# 3 times 'un', followed by 'ium'
3 * 'un' + 'ium'

输出为:

'unununium'

如果将运算顺序应用于运算符,则用于字符串时和用于数字类型时采用的方式一样。 用不同的运算符和字符串组合与顺序实验一下,看看会发生什么情况。

连接字符串

两个或多个彼此相邻的字符串文本自动串联:

'Py' 'thon'

输出为:

'Python'

但是,若要将变量或将变量和文本进行串联,请使用加号运算符 (+):

prefix = 'Py'
prefix + 'thon'

输出为:

'Python'