Python字符串串联

时间:2020-02-23 14:43:23  来源:igfitidea点击:

字符串连接是编程中非常常见的操作。
Python字符串串联可以使用多种方式来完成。
本教程旨在探索在python程序中连接字符串的不同方法。

Python字符串串联

我们可以使用以下方式执行字符串连接:

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

使用+运算符的字符串连接

这是字符串连接的最简单方法。
让我们看一个简单的例子。

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 theitroad - %d" % (s1, s2, 2016)
print('String Concatenation using % Operator with Formatting =', s3)

输出:

String Concatenation using % Operator = Hello World
String Concatenation using % Operator with Formatting = Hello World from theitroad - 2016

使用format()函数的字符串连接

我们也可以使用string 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字符串format()函数非常强大,仅将其用于字符串连接是不合适的。

使用f字符串的字符串连接

如果您使用的是Python 3.6+,则也可以使用f-string进行字符串连接。
这是一种格式化字符串的新方法,并在PEP 498(文字字符串插值)中引入。

s1 = 'Hello'
s2 = 'World'

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

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

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

输出:

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

与format()函数相比,Python f字符串更干净,更易于编写。
当将对象参数用作字段替换时,它还会调用str()函数。