共計 615 個字符,預計需要花費 2 分鐘才能閱讀完成。
Python 字符串拼接的方法有以下幾種:
- 使用 "+“符號進行拼接:可以使用”+" 符號將兩個或多個字符串拼接在一起,例如:
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # 輸出:Hello World
- 使用 join() 方法進行拼接:可以使用 join() 方法將一個字符串列表或元組拼接成一個字符串,例如:
str_list = ["Hello", "World"]
result = " ".join(str_list)
print(result) # 輸出:Hello World
- 使用格式化字符串進行拼接:可以使用格式化字符串的方式將變量或表達式插入到字符串中,例如:
name = "Alice"
age = 25
result = "My name is %s and I am %d years old." % (name, age)
print(result) # 輸出:My name is Alice and I am 25 years old.
- 使用 f -string 進行拼接:可以使用 f -string 的方式將變量或表達式插入到字符串中,例如:
name = "Alice"
age = 25
result = f"My name is {name} and I am {age} years old."
print(result) # 輸出:My name is Alice and I am 25 years old.
以上是常用的字符串拼接方法,根據具體的需求選擇合適的方法。
丸趣 TV 網 – 提供最優質的資源集合!
正文完