在Python中使用字符串

Python中的字符串基础知识

简单的字符串

在本单元的示例中,你有一个关于月球的事实,它被赋值到一个变量,如下所示:

python 复制代码
fact = "The Moon has no atmosphere."
print(fact)

字符串的不可变性

在 Python 中,字符串是不可变的。 也就是说,它们不能更改。 字符串类型的此属性可能令人感到惊讶,因为在你更改字符串时,Python 不会显示错误。

你需要向已被赋值到一个变量的该事实添加另一个事实(句子)。 添加第二个事实似乎会改变变量,如以下示例所示:

python 复制代码
fact = "The Moon has no atmosphere."
fact + "No sound can be heard on the Moon."

你可能希望输出为:The Moon has no atmosphere.No sound can be heard on the Moon.

尽管可能看起来我们已经修改了变量 fact,但快速检查值后发现原始值没有变化:

输出:The Moon has no atmosphere.

技巧在于必须使用返回值。 添加字符串时,Python 不会修改任何字符串,但会返回一个新的字符串作为结果。 若要保留这个新结果,请将它分配给新变量:

python 复制代码
fact = "The Moon has no atmosphere."
two_facts = fact + "No sound can be heard on the Moon."
print(two_facts)

输出:The Moon has no atmosphere.No sound can be heard on the Moon.

操作字符串始终会生成新的字符串作为结果。

关于使用引号

可以用单引号、双引号或三引号将 Python 字符串引起来。 尽管可互换使用它们,但最好在项目中一致地使用一种类型。 例如,以下字符串使用双引号:

python 复制代码
moon_radius = "The Moon has a radius of 1,080 miles."

但是,如果字符串包含也用引号引起来的单词、数字或特殊字符(子字符串),则应使用其他样式。 例如,如果子字符串使用双引号,那么请用单引号将整个字符串引起来,如下所示:

python 复制代码
'The "near side" is the part of the Moon that faces the Earth.'

同样,如果在字符串中的任何位置有单引号(或撇号,如下例中的 Moon's 所示),请用双引号将整个字符串引起来:

python 复制代码
"We only see about 60% of the Moon's surface."

如果不能替换单引号和双引号,可能会导致 Python 解释器引发语法错误,如下所示:

原因在于引号,括号均是就近匹对原则

python 复制代码
'We only see about 60% of the Moon's surface.'
  File "<stdin>", line 1
    'We only see about 60% of the Moon's surface.'
                                       ^
SyntaxError: invalid syntax

如果文本包含单引号和双引号的组合,可使用三引号来防止解释器出现问题:

python 复制代码
"""We only see about 60% of the Moon's surface, this is known as the "near side"."""

多行文本

有几种不同的方法可将多行文本定义为单个变量。 最常见的方法是:

使用换行符 (\n)。

使用三引号 (""")。

打印输出时,换行符将文本分隔到多行:

python 复制代码
multiline = "Facts about the Moon:\n There is no atmosphere.\n There is no sound."
print(multiline)
python 复制代码
Facts about the Moon:
 There is no atmosphere.
 There is no sound.

可使用三引号到达这一目的:

python 复制代码
multiline = """Facts about the Moon:
 There is no atmosphere. 
 There is no sound."""
print(multiline)
相关推荐
虾球xz11 分钟前
CppCon 2015 学习:Give me fifteen minutes and I’ll change your view of GDB
开发语言·c++·学习
alpszero21 分钟前
使用VSCode开发Django指南
vscode·python·django·sqlite
大数据魔法师32 分钟前
MongoDB(八) - MongoDB GridFS介绍及使用Python操作GridFS
数据库·python·mongodb
weixin_377634841 小时前
【python异步多线程】异步多线程爬虫代码示例
开发语言·爬虫·python
struggle20251 小时前
PennyLane 是一个用于量子计算、量子机器学习和量子化学的跨平台 Python 库。由研究人员构建,用于研究
python·量子计算
扑克中的黑桃A1 小时前
Python-素数
python
扑克中的黑桃A1 小时前
Python学习的自我理解和想法(4)
python
扑克中的黑桃A1 小时前
Python-打印杨辉三角(进阶版)
python
随意0231 小时前
STL 6分配器
开发语言·c++
laity172 小时前
激活IDM的几种方法
python