在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)
相关推荐
Highcharts.js3 分钟前
在Python中配置高度交互的数据可视化:Highcharts完全指南
开发语言·python·信息可视化·highcharts
小生凡一6 分钟前
图解|Go语言实现 Agent|LLM+MCP+RAG
开发语言·后端·golang
思茂信息17 分钟前
CST电动车EMC仿真(二)——电机控制器MCU的EMC仿真
开发语言·javascript·单片机·嵌入式硬件·cst·电磁仿真
Ace_317508877620 分钟前
京东关键字搜索接口逆向:从动态签名破解到分布式请求调度
分布式·python
开始了码41 分钟前
关于qt运行程序点击几下未响应的原因
开发语言·qt
QT 小鲜肉42 分钟前
【QT/C++】Qt样式设置之CSS知识(系统性概括)
linux·开发语言·css·c++·笔记·qt
yachuan_qiao44 分钟前
专业的建筑设备监控管理系统选哪家
大数据·运维·python
洛克希德马丁1 小时前
Qt配置安卓开发环境
android·开发语言·qt
我要升天!1 小时前
QT-- 理解项目文件
开发语言·数据库·qt
l1t1 小时前
DeepSeek辅助编写转换DuckDB json格式执行计划到PostgreSQL格式的Python程序
数据库·python·postgresql·json·执行计划