Python 中有多种方法可以连接字符串,每种方法都有其自身的特点和适用场景。在本文中,我们将介绍 Python 中五种常用的字符串连接方法,并附上相应的代码示例。
方法一:使用加号 +
<code>str1 = "Hello" str2 = "World" result = str1 + " " + str2 print(result) # Output: Hello World</code>
方法二:使用字符串的 join()
方法
<code>str_list = ["Hello", "World"] result = " ".join(str_list) print(result) # Output: Hello World</code>
方法三:使用 %
格式化字符串
<code>str1 = "Hello" str2 = "World" result = "%s %s" % (str1, str2) print(result) # Output: Hello World</code>
方法四:使用 format()
方法
<code>str1 = "Hello" str2 = "World" result = "{} {}".format(str1, str2) print(result) # Output: Hello World</code>
方法五:使用 f-string(格式化字符串字面值)
<code>str1 = "Hello" str2 = "World" result = f"{str1} {str2}" print(result) # Output: Hello World</code>
以上是 Python 中常用的五种字符串连接方法。你可以根据具体情况选择最适合你的方法。
© 版权声明
THE END
暂无评论内容