在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)
相关推荐
兮兮能吃能睡4 分钟前
资料片:R语言中常见的英文术语及其含义
开发语言·r语言
zz-zjx11 分钟前
JVM垃圾收集器详解(jdk21+25实战版)
java·开发语言·jvm
郝学胜-神的一滴17 分钟前
Linux系统函数link、unlink与dentry的关系及使用注意事项
linux·运维·服务器·开发语言·前端·c++
赵杰伦cpp19 分钟前
list的迭代器
开发语言·数据结构·c++·算法·链表·list
wan了个蛋30 分钟前
使用python脚本大批量自动化处理图片上的ai水印
python
好家伙VCC43 分钟前
**TensorFlow:发散创新的深度学习框架探索**随着人工智
java·人工智能·python·深度学习·tensorflow
YFLICKERH1 小时前
【多进线程】python多进线程与通信
python
_extraordinary_1 小时前
Java Spring配置
java·开发语言·spring
程序员爱钓鱼1 小时前
Python编程实战 · 基础入门篇 | 第一个Python程序:Hello World
后端·python·编程语言
进击的大海贼2 小时前
QT-C++ 自定义加工统计通用模块
开发语言·c++·qt