在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)
相关推荐
都叫我大帅哥1 小时前
Python的Optional:让你的代码优雅处理“空值”危机
python
曾几何时`3 小时前
基于python和neo4j构建知识图谱医药问答系统
python·知识图谱·neo4j
古月-一个C++方向的小白5 小时前
C++11之lambda表达式与包装器
开发语言·c++
写写闲篇儿5 小时前
Python+MongoDB高效开发组合
linux·python·mongodb
沐知全栈开发5 小时前
Eclipse 生成 jar 包
开发语言
杭州杭州杭州6 小时前
Python笔记
开发语言·笔记·python
tanyongxi667 小时前
C++ AVL树实现详解:平衡二叉搜索树的原理与代码实现
开发语言·c++
阿葱(聪)8 小时前
java 在k8s中的部署流程
java·开发语言·docker·kubernetes
路人蛃8 小时前
通过国内扣子(Coze)搭建智能体并接入discord机器人
人工智能·python·ubuntu·ai·aigc·个人开发
qiqiqi(^_×)8 小时前
卡在“pycharm正在创建帮助程序目录”
ide·python·pycharm