溫馨提示×

Python字符串拼接的方法有哪些

小億
103
2023-11-14 01:57:29
欄目: 編程語言

Python字符串拼接的方法有以下幾種:

  1. 使用"+“符號進行拼接:可以使用”+"符號將兩個或多個字符串拼接在一起,例如:
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result)  # 輸出:Hello World
  1. 使用join()方法進行拼接:可以使用join()方法將一個字符串列表或元組拼接成一個字符串,例如:
str_list = ["Hello", "World"]
result = " ".join(str_list)
print(result)  # 輸出:Hello World
  1. 使用格式化字符串進行拼接:可以使用格式化字符串的方式將變量或表達式插入到字符串中,例如:
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.
  1. 使用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.

以上是常用的字符串拼接方法,根據具體的需求選擇合適的方法。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女