ZetCode

Python 字符串相加

最后修改于 2024 年 1 月 29 日

Python 字符串相加教程展示了如何在 Python 中连接字符串。

在 Python 中,字符串是 Unicode 字符的有序序列。

在 Python 中添加字符串的几种方法:

使用 + 运算符添加 Python 字符串

连接字符串最简单的方法是使用 ++= 运算符。+ 运算符既用于添加数字也用于添加字符串;在编程中,我们称该运算符是重载的。

add_string.py
#!/usr/bin/python

a = 'old'
b = ' tree'

c = a + b
print(c)

使用 + 运算符添加两个字符串。

$ ./add_string.py 
old tree

在第二个示例中,我们使用了复合加法运算符。

add_string2.py
#!/usr/bin/python

msg = 'There are'

msg += ' three falcons'
msg += ' in the sky'

print(msg)

该示例使用 += 运算符构建消息。

$ ./add_string2.py 
There are three falcons in the sky

使用 join 添加 Python 字符串

字符串 join 方法可以连接可迭代对象(元组、列表)中的任意数量的字符串。我们指定用来连接字符串的字符。

add_string_join.py
#!/usr/bin/python

msg = ' '.join(['There', 'are', 'three', 'eagles', 'in', 'the', 'sky'])
print(msg)

在示例中,我们通过连接七个单词来形成一个消息。这些单词用单个空格字符连接。

$ ./add_string_join.py
There are three eagles in the sky

使用字符串格式化添加 Python 字符串

我们可以使用字符串格式化来构建 Python 字符串。变量会被展开到字符串中的 {} 字符内。

format_str.py
#!/usr/bin/python

w1 = 'two'
w2 = 'eagles'

msg = f'There are {w1} {w2} in the sky'
print(msg)

我们使用 Python 的 f-string 构建了一个消息。

$ ./format_str.py 
There are two eagles in the sky

使用 __add__ 方法添加 Python 字符串

添加字符串的另一种可能性是使用特殊的 __add__ 双下划线方法。

add_string3.py
#!/usr/bin/python

s1 = "and old"
s2 = " falcon"

s3 = s1.__add__(s2)
print(s3)

该示例使用 __add__ 添加了两个字符串。

来源

Python 常用字符串操作

在本文中,我们展示了在 Python 中添加字符串的几种方法。

作者

我的名字是 Jan Bodnar,我是一名充满热情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直撰写编程文章。迄今为止,我已撰写了 1,400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出所有 Python 教程