Python字符串串接

字串串接是編程中非常常見的操作。Python 字串串接可以使用各種方式完成。本教程旨在探索 Python 程式中串接字串的不同方法。

Python 字串串接

我們可以使用以下方式執行字串串接:

  • 使用 + 運算子
  • 使用 join() 方法
  • 使用 % 運算子
  • 使用 format() 函數
  • 使用 f-string(Literal String Interpolation)

使用 + 運算子進行字串串接

這是最簡單的字串串接方式。讓我們看一個簡單的例子。

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()`函數來使用分隔符連接字符串。當我們有一系列字符串時,例如字符串的`list`或`tuple`時,這很有用。如果您不想要分隔符,那麼請使用帶有空字符串的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-string進行字符串串聯

如果您使用的是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]

與format()函數相比,Python的f-string更清潔、更容易撰寫。當將對象參數用作字段替換時,它還會調用str()函數。

結論

Python 字串格式化可以用幾種方式進行。根據您的需求使用它們。如果您需要連接一系列帶有分隔符的字串,則使用 join() 函數。如果連接時還需要進行一些格式化,則使用 format() 函數或 f-string。請注意,f-string 只能在 Python 3.6 或以上版本中使用。

您可以從我們的 GitHub 存儲庫中查看完整的 Python 腳本和更多 Python 範例。

Source:
https://www.digitalocean.com/community/tutorials/python-string-concatenation