如何在 Python 中不使用 '+' 運算子進行字串連線?


在本文中,我們將瞭解如何在 Python 中不使用加號運算子進行字串連線。

第一種方法是利用字串內建庫的 **join()** 方法。此方法用於使用分隔符連線字串。此方法的輸出是一個字串序列。

Python 的 **join()** 方法提供了連線由字串運算子分隔的可迭代元件的能力。要返回一個帶有用字串分隔符連線的序列項的迭代器的字串,請使用 Python 內建的 join 函式。

示例 1

在下面的示例中,我們取兩個字串作為輸入,並使用 **join()** 方法用空格連線它們。

str1 = "Welcome"
str2 = "Tutorialspoint"

print("The first string is")
print(str1)

print("The second string is")
print(str2)

concat = " ".join([str1,str2])
print("The concatenated string is")
print(concat)

輸出

上面示例的輸出如下:

The first string is
Welcome
The second string is
Tutorialspoint
The concatenated string is
Welcome Tutorialspoint

示例 2

在下面的程式中,我們使用與上面相同的程式,但是我們使用空字串連線輸入字串。

str1 = "Welcome"
str2 = "Tutorialspoint"

print("The first string is")
print(str1)

print("The second string is")
print(str2)

concat = "".join([str1,str2])
print("The concatenated string is")
print(concat)

輸出

上面示例的輸出如下:

The first string is
Welcome
The second string is
Tutorialspoint
The concatenated string is
WelcomeTutorialspoint

示例 3

在下面的示例中,我們使用與上面相同的程式,但是我們使用 ',' 運算子進行連線。

str1 = "Welcome"
str2 = "Tutorialspoint"

print("The first string is")
print(str1)

print("The second string is")
print(str2)

concat = ",".join([str1,str2])
print("The concatenated string is")
print(concat)

輸出

上面示例的輸出如下所示:

The first string is
Welcome
The second string is
Tutorialspoint
The concatenated string is
Welcome,Tutorialspoint

使用 filter() 方法

第二種方法是使用字串庫中的 **format()** 函式,這是一個內建方法。它主要用於在列印語句中包含變數。我們將使用雙引號中的花括號來指示某個變數的存在,然後在 **format()** 函式內指定變數名。

示例

在下面的示例中,我們取兩個字串作為輸入,並使用 **filter()** 操作進行連線。

str1 = "Welcome"
str2 = "Tutorialspoint"

print("The first string is")
print(str1)

print("The second string is")
print(str2)

concat = "{} {}".format(str1, str2)
print("The concatenated string is")
print(concat)

輸出

上面示例的輸出如下所示:

The first string is
Welcome
The second string is
Tutorialspoint
The concatenated string is
Welcome Tutorialspoint

更新於:2022年12月7日

2K+ 瀏覽量

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.