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-tw/n/238638.html