Python字符串连接

0 股票
0
0
0
0

介绍

字符串连接是编程中非常常见的操作。Python 可以使用多种方法实现字符串连接。本教程旨在探讨在 Python 程序中连接字符串的不同方法。.

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

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

s1 = 'Apple'
s2 = 'Pie'
s3 = 'Sauce'
s4 = s1 + s2 + s3
print(s4)

输出:  苹果派酱 让我们来看另一个例子,其中我们从用户输入接收两个字符串并将它们连接起来。.

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”,则需要这样写: ""你好" + " " + "世界"" 我们开始写作吧。.

使用 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 的字符串 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 = '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 函数(字符串)比 format() 函数更简洁易写。此外,当对象参数用作字段替换时,它还会调用 str() 函数。.

结果

Python 字符串格式化有多种方法,您可以根据需要选择合适的方法。如果您需要用分隔符连接一系列字符串,请使用 `join()` 函数。如果连接后还需要进行格式化,请使用 `format()` 或 `f-string` 函数。请注意,`f-string` 函数仅适用于 Python 3.6 及更高版本。.

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

您可能也喜欢

战神2游戏剧情

引言:奎托斯,这位曾经的凡人战士,击败了战神阿瑞斯,成为了新的战神。然而……