Python字符串追加简介及实例

853 阅读5分钟

Python string append

Python字符串追加介绍

在这篇文章中,我们讨论了字符串的连接以及如何将一个字符串追加到另一个字符串上。在Python中,我们也可以重复地追加字符串。在Python中,连接意味着将一个字符串添加或追加到另一个字符串。通常,Python的 "+"运算符用于将一个字符串添加到另一个字符串,即把一个变量添加到另一个变量。在Python中,我们也有append()函数,它将在现有的项目中增加一个单项。这个函数在对现有元素应用这个append()函数后,将返回修改后的项目列表。还有一个方法叫join(),它也用于追加字符串。

字符串追加的工作原理及实例

在这篇文章中,我们将看到Python中的append()函数,还将看到其他附加或串联字符串的方法。 正如我们所知,字符串的对象是不可改变的;当我们使用 "+"运算符连接字符串时,会产生一个新的不同的字符串。而对字符串的追加只是修改原来的字符串,这也与使用 "+"运算符类似。这个附加函数主要用于字符串的列表。为了重复追加字符串,我们需要首先将其转换为一个列表,然后将给定的元素追加到该列表中,再将该列表连接回追加的字符串。

现在让我们看看如何使用 "+"运算符追加一个字符串,这也被称为字符串的连接。让我们看看下面的例子,它使用 "+"运算符来连接给定的字符串。

例子

str1 = "Educba Training"
str2 = " MuMbai, India"
print("The given original string : " + str(str1))
print("The string given to append to the previous string: " + str(str2))
res = str1 + str2
print("The Modified string is obtained as follows:")
print(res)

输出

python string append output 1

在上面的程序中,我们看到有两个字符串,"str1 "和 "str2",使用 "+"运算符将str1与str2相连接。这是在语句 "res = str1 + str2 "中完成的,我们将字符串1与strin2相加,得到结果,该结果存储在变量 "res "中。结果是两个字符串的相加,或者我们可以说str2被附加在str1上。我们可以看到str2以空白开始,这样当它被附加到str1上时,我们就可以正确地阅读它。

现在让我们看看如何使用append()函数来追加两个字符串。这个函数的工作原理也类似于上面的 "+"运算符。让我们看看下面这个使用append()函数的例子。这个函数主要用于追加两个以上的字符串。

语法

str.append(items)

要添加到字符串列表中的项目。

这将在给定的字符串或字符串列表中增加一个单项。

例子

str = ['Educba', 'Training', 'Institute']
print("The given original strings are as follows:")
print(str)
str.append('Mumbai India')
print("Appended string is as follows:")
print(str)

输出

python string append output 2

在上面的程序中,我们看到列表中的字符串是用 "str "变量声明的,需要添加的字符串可以直接传递给append()函数。我们应该注意,在这里我们只能向字符串列表中添加一个项目。所以要对字符串列表对象做这件事,我们应该应用append()函数。因此,这是追加字符串的一种方法。

假设我们想在给定的字符串列表中添加一个以上的项目,也就是把一个字符串列表添加到另一个字符串列表中,可以按以下方法进行。

例子

str1 = ['Educba', 'Training', 'Institute']
print("The first string list is given as follows:")
print(str1)
str2 = ['Bangalore', 'India']
print("The second string list that needs to be appneded to the first string list is as follows")
print(str2)
str1.append(str2)
print("The modified string list after appending is as follows:")
print(str1)

输出

python string append output 3

在上面的程序中,我们可以看到我们有两个字符串列表,其中str2需要被追加到str1中,结果得到的是一个单一的字符串被追加到第二个字符串中。在上面的截图中,我们可以看到第二个字符串列表被追加到第一个字符串列表中。

现在让我们看看另一种使用Python中的join()函数追加字符串的方法。让我们考虑下面的例子来演示 join() 函数。当我们需要添加更多的字符串而不是两个字符串时,这个函数很有用。

例子

str1 = "Educba Training"
str2 = " Mumbai India"
print("The given first string : " )
print(str(str1))
print("The given second string that needs to be appended: ")
print(str(str2))
res = "".join((str1, str2))
print("The appended string is obtained as follows: ")
print(res)

输出

output 4

在上面的程序中,我们看到了另一种追加字符串的方法。在上面的程序中,我们看到使用join"()函数;我们可以将第二个字符串追加到第一个字符串上。

总结

在这篇文章中,我们讨论了 Python 中的字符串追加。字符串追加本身意味着在给定的字符串或字符串列表中连接或添加两个或更多的字符串,以获得包含两个字符串或字符串列表的修改后的字符串;在这篇文章中,我们首先看到了如何使用 "+"运算符追加到两个字符串。然后,我们看到了append(),它用于用一个字符串或多个字符串来追加字符串列表。最后,我们看到了join()函数,它被用来追加字符串,其中它也可以用来追加一个以上的字符串。