在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)
相关推荐
星秀日3 分钟前
框架--SpringMVC
java·开发语言·servlet
布林模型35 分钟前
缠论工具czsc快速使用入门(二)
python·缠论·快速入门·czsc
邂逅you1 小时前
用python操作mysql之pymysql库基本操作
数据库·python·mysql
啊森要自信1 小时前
【GUI自动化测试】YAML 配置文件应用:从语法解析到 Python 读写
android·python·缓存·pytest·pip·dash
勤奋菲菲1 小时前
Vue3+Three.js:requestAnimationFrame的详细介绍
开发语言·javascript·three.js·前端可视化
合作小小程序员小小店1 小时前
web开发,学院培养计划系统,基于Python,FlaskWeb,Mysql数据库
后端·python·mysql·django·web app
要天天开心啊1 小时前
Java序列化和反序列化
java·开发语言
渣渣盟1 小时前
解密NLP:从入门到精通
人工智能·python·nlp
老程序员刘飞1 小时前
注册 区块链节点
python
KAIWEILIUCC1 小时前
Python抽象基类(abc.ABC)介绍
python