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


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

第一個技巧是利用字串內建庫的 join() 方法。使用此方法來混合帶有分隔符的字串。此方法會生成一個字串序列作為輸出。

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

示例 1

在下面給出的示例中,我們以 2 個字串作為輸入,並使用 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() 函式內部指定變數名。

示例

在下面給出的示例中,我們以 2 個字串作為輸入,並使用 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-07

2K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.