python3 拼接字符串的7种方法

   2025-02-19 2740
核心提示:使用加号运算符 “+”str1 = Hellostr2 = Worldresult = str1 + + str2print(result)# Output: Hello World使用逗号分隔的多个字

使用加号运算符 “+”

str1 = "Hello"str2 = "World"result = str1 + " " + str2print(result)  # Output: Hello World
使用逗号分隔的多个字符串
str1 = "Hello"str2 = "World"print(str1, str2)  # Output: Hello World
使用字符串的 join() 方法
str1 = "Hello"str2 = "World"result = " ".join([str1, str2])print(result)  # Output: Hello World
使用 f-string 格式化字符串
str1 = "Hello"str2 = "World"result = f"{str1} {str2}"print(result)  # Output: Hello World
使用字符串的 format() 方法
str1 = "Hello"str2 = "World"result = "{} {}".format(str1, str2)print(result)  # Output: Hello World
使用字符串的 % 格式化
str1 = "Hello"str2 = "World"result = "%s %s" % (str1, str2)print(result)  # Output: Hello World
使用列表推导式和字符串的 join() 方法
str1 = "Hello"str2 = "World"result = " ".join([word for word in [str1, str2]])print(result)  # Output: Hello World

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言