Python字符串连接

字符串拼接是编程中非常常见的操作。Python字符串拼接可以通过各种方式完成。本教程旨在探讨在Python程序中拼接字符串的不同方法。

Python字符串拼接

我们可以使用以下方式进行字符串拼接:

  • 使用+运算符
  • 使用join()方法
  • 使用%运算符
  • 使用format()函数
  • 使用f-string(字面字符串插值)

使用+运算符进行字符串拼接

这是最简单的字符串拼接方式。让我们看一个简单的示例。

s1 = 'Apple'
s2 = 'Pie'
s3 = 'Sauce'

s4 = s1 + s2 + s3

print(s4)

输出:ApplePieSauce 让我们再看另一个例子,我们将从用户输入获取两个字符串并将它们拼接起来。

s1 = input('Please enter the first string:\n')
s2 = input('Please enter the second string:\n')

print('Concatenated String =', s1 + s2)

输出:

Please enter the first string:
Hello
Please enter the second string:
World
Concatenated String = HelloWorld

使用+运算符进行字符串拼接非常简单。但是,参数必须是字符串。

>>>'Hello' + 4
Traceback (most recent call last):
  File "<input>", line 1, in 
TypeError: can only concatenate str (not "int") to str

我们可以使用str()函数来获取对象的字符串表示。让我们看看如何将字符串连接到整数或其他对象。

print('Hello' + str(4))


class Data:
    id = 0

    def __init__(self, i):
        self.id = i

    def __str__(self):
        return 'Data[' + str(self.id) + ']'


print('Hello ' + str(Data(10)))

输出:

Hello4
Hello Data[10]

使用+运算符的最大问题是我们无法在字符串之间添加任何分隔符。例如,如果我们必须用空格分隔符连接“Hello”和“World”,我们将不得不这样写:"Hello" + " " + "World"

使用join()函数进行字符串连接

我们可以使用join()函数来用分隔符连接字符串。当我们有一系列字符串时很有用,例如列表元组中的字符串。如果不想要分隔符,请使用带有空字符串的join()函数。

s1 = 'Hello'
s2 = 'World'

print('Concatenated String using join() =', "".join([s1, s2]))

print('Concatenated String using join() and whitespaces =', " ".join([s1, s2]))

输出:

Concatenated String using join() = HelloWorld
Concatenated String using join() and spaces = Hello World

使用%运算符进行字符串连接

我们可以使用%运算符进行字符串格式化,它也可以用于字符串拼接。当我们想要连接字符串并执行简单格式化时,它非常有用。

s1 = 'Hello'
s2 = 'World'

s3 = "%s %s" % (s1, s2)
print('String Concatenation using % Operator =', s3)

s3 = "%s %s from JournalDev - %d" % (s1, s2, 2018)
print('String Concatenation using % Operator with Formatting =', s3)

输出:

String Concatenation using % Operator = Hello World
String Concatenation using % Operator with Formatting = Hello World from JournalDev - 2018

使用format()函数进行字符串拼接

我们还可以使用字符串的format()函数进行字符串拼接和格式化。

s1 = 'Hello'
s2 = 'World'

s3 = "{}-{}".format(s1, s2)
print('String Concatenation using format() =', s3)

s3 = "{in1} {in2}".format(in1=s1, in2=s2)
print('String Concatenation using format() =', s3)

输出:

String Concatenation using format() = Hello-World
String Concatenation using format() = Hello World

Python的String format()函数非常强大,仅将其用于字符串拼接并不是其正确的用法。

使用f-string进行字符串拼接

如果你使用的是Python 3.6+,你还可以使用f-string进行字符串拼接。这是一种新的字符串格式化方式,引入自PEP 498 – Literal String Interpolation

s1 = 'Hello'
s2 = 'World'

s3 = f'{s1} {s2}'
print('String Concatenation using f-string =', s3)

name = 'Pankaj'
age = 34
d = Data(10)

print(f'{name} age is {age} and d={d}')

输出:

String Concatenation using f-string = Hello World
Pankaj age is 34 and d=Data[10]

Python的f-string相对于format()函数更清晰、更容易书写。当对象参数用作字段替换时,它还会调用str()函数。

结论

Python字符串格式化可以通过多种方式完成。根据您的需求使用它们。如果您需要连接一系列带有分隔符的字符串,则使用join()函数。如果连接时还需要进行一些格式化,则使用format()函数或f-string。请注意,f-string只能在Python 3.6或以上版本中使用。

您可以从我们的GitHub代码库检查完整的Python脚本和更多Python示例。

Source:
https://www.digitalocean.com/community/tutorials/python-string-concatenation