在Python中合并字符串的详细教程

528 阅读2分钟

Python字符串是一个代表Unicode字符的字节数组。字符串是不可变的,意味着在创建后不能被改变。在这篇文章中,我们将看到如何使用各种方法和手段来组合字符串。

Python组合字符串

要在Python中组合字符串,可以使用连接(+)运算符。连接运算符将一个变量添加到另一个变量中。连接意味着得到一个包含两个原始字符串的新字符串。

如果你看到组合、协程或合并这样的词,都是同一个意思。合并多个不同的字符串,做成一个字符串。

合并字符串的实现

声明两个字符串,并使用concat(+)操作符将其合并:

minerva = "Piertotum Locomotor"

dumbledore = "Partis Temporus"

war_spells = minerva + " " + dumbledore

print(war_spells)

输出

Piertotum Locomotor Partis Temporus

我们就把两个字符串合并成了一个。

对于数字,"+"字符作为一个数学运算符,将两个数字相加。

minerva = 19

dumbledore = 21

war_spells = minerva + dumbledore

print(war_spells)

输出

40

字符串组合中的错误

如果你用+运算符组合字符串和数字,那么会出现错误:

minerva = 19

dumbledore = "Explelliarmus"

war_spells = minerva + dumbledore

print(war_spells)

输出

Traceback (most recent call last):
  File "/Users/krunal/Desktop/code/pyt/database/app.py", line 5, in <module>
    war_spells = minerva + dumbledore
TypeError: unsupported operand type(s) for +: 'int' and 'str'

你不能合并字符串和整数变量;否则,你会得到一个TypeError

使用join()方法合并字符串

join() 是一个内置的 Python 方法,它返回一个字符串,其中的序列元素已经被一个字符串分隔符连接起来。

join()方法结合了存储在第一个变量和第二个变量中的字符串。join() 方法只接受列表作为它的参数,而列表的大小可以是任何东西。

minerva = "Piertotum Locomotor"

dumbledore = "Explelliarmus"

war_spells = " ".join([minerva, dumbledore])

print(war_spells)

输出

Piertotum Locomotor Explelliarmus

使用%操作符连接字符串

要在 Python 中连接字符串,可以使用 % 操作符。这个 % 操作符在字符串格式化中也很有用:

minerva = "Piertotum Locomotor"

dumbledore = "Explelliarmus"

print("% s % s" % (minerva, dumbledore))

输出

Piertotum Locomotor Explelliarmus

在这个例子中,%操作符结合了存储在两个变量中的字符串,%s 表示字符串的数据类型。

使用format()函数

string.format()函数允许多种替换和数值格式化,并让我们通过位置格式化将字符串中的项目连接起来:

minerva = "Piertotum Locomotor"

dumbledore = "Explelliarmus"

op = "{} {}".format(minerva, dumbledore)

print(op)

输出

Piertotum Locomotor Explelliarmus

在这个例子中,format()方法合并了存储在两个变量中的字符串并存储在另一个变量op中。

本教程就到此为止。

参见

Python 字符串连接

Python字符串置换