共計 592 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Python 中,字符串的拼接可以使用以下幾種方法:
- 使用 ”+” 運算符進行拼接:
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # 輸出:Hello World
- 使用字符串的 join() 方法進行拼接:
str_list = ["Hello", "World"]
result = " ".join(str_list)
print(result) # 輸出:Hello World
- 使用 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.
- 使用格式化字符串進行拼接:
name = "Alice"
age = 25
result = "My name is {} and I am {} years old.".format(name, age)
print(result) # 輸出:My name is Alice and I am 25 years old.
- 使用字符串的切片和拼接操作:
str1 = "Hello"
str2 = "World"
result = str1[:2] + str2[2:]
print(result) # 輸出:Horld
以上是幾種常見的字符串拼接方法,選擇適合你的場景進行使用。
丸趣 TV 網 – 提供最優質的資源集合!
正文完