Python 添加字符串

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

Python教程是Python语言的综合教程。

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

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

  • +运算符
  • __add__方法
  • join方法
  • 格式化字符串

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

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

#!/usr/bin/python

a = 'old'
b = ' tree'

c = a + b
print(c)

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

$ ./add_string.py 
old tree

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

#!/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

Python用join添加字符串

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

#!/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字符串。变量在字符串内的{}字符中展开。

#!/usr/bin/python

w1 = 'two'
w2 = 'eagles'

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

我们使用Python的fstring构建消息。

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

Python用__add_方法添加字符串

另一种添加字符串的可能性是使用特殊的__add__dunder方法。

#!/usr/bin/python

s1 = "and old"
s2 = " falcon"

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

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

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

阅读Python教程或列出所有Python教程。

赞(0) 打赏

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏