Python 字符串是 Unicode 字符的集合。Python 為字符串操作提供了許多內置函數。字符串串聯是一個字符串與另一個字符串合併的過程。可以通過以下方式完成。
- 使用+運算符
- 使用 join()方法
- 使用%方法
- 使用 format()函數
讓我們理解下面的字符串連接方法。
使用+運算符
這是一種組合兩個字符串的簡單方法。+運算符將多個字符串相加。字符串必須分配給不同的變量,因為字符串是不可變的。讓我們理解下面的例子。
示例-
# Python program to show
# string concatenation
# Defining strings
str1 = "Hello "
str2 = "Devansh"
# + Operator is used to strings concatenation
str3 = str1 + str2
print(str3) # Printing the new combined string
輸出:
Hello Devansh
說明:
在上面的例子中,變量 str1 存儲字符串“Hello”,變量 str2 存儲“Devansh”。我們使用+運算符組合這兩個字符串變量並存儲在 str3 中。
使用 join()方法
join()方法用於連接字符串,其中字符串分隔符連接了序列元素。讓我們理解下面的例子。
示例-
# Python program to
# string concatenation
str1 = "Hello"
str2 = "JavaTpoint"
# join() method is used to combine the strings
print("".join([str1, str2]))
# join() method is used to combine
# the string with a separator Space(" ")
str3 = " ".join([str1, str2])
print(str3)
輸出:
HelloJavaTpoint
Hello JavaTpoint
說明:
在上面的代碼中,變量 str1 存儲字符串“Hello”,變量 str2 存儲“JavaTpoint”。join()方法返回存儲在 str1 和 str2 中的組合字符串。join()方法只接受列表作為參數。
使用%運算符
%運算符用於字符串格式。它也可以用於字符串連接。讓我們理解下面的例子。
示例-
# Python program to demonstrate
# string concatenation
str1 = "Hello"
str2 = "JavaTpoint"
# % Operator is used here to combine the string
print("% s % s" % (str1, str2))
輸出:
Hello JavaTpoint
解釋-
在上面的代碼中,%s 代表字符串數據類型。我們將兩個變量的值傳遞給組合字符串的%s,並返回“你好 JavaTpoint”。
使用 format()函數
Python 提供了 str.format() 功能,允許使用多個替換和值格式。它接受位置參數,並通過位置格式連接字符串。讓我們理解下面的例子。
示例-
# Python program to show
# string concatenation
str1 = "Hello"
str2 = "JavaTpoint"
# format function is used here to
# concatenate the string
print("{} {}".format(str1, str2))
# store the result in another variable
str3 = "{} {}".format(str1, str2)
print(str3)
輸出:
Hello JavaTpoint
Hello JavaTpoint
說明:
在上面的代碼中,format()函數將兩個字符串組合併存儲到 str3 變量中。大括號{}用作字符串的位置。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/238638.html