学堂 学堂 学堂公众号手机端

Python中的字符串拼接

lewis 3年前 (2022-11-13) 阅读数 4 #技术

在Python中,有多种方法可以拼接字符串,以下是一些常用的方法:

1、使用加号(+)拼接字符串

2、使用字符串的join()方法拼接字符串


3、使用格式化字符串(fstring)拼接字符串

4、使用字符串格式化(%)拼接字符串

5、使用字符串格式化(format())拼接字符串

下面是详细的解释和示例代码:

1. 使用加号(+)拼接字符串

str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result)  # 输出:Hello World

2. 使用字符串的join()方法拼接字符串

str_list = ["Hello", "World"]
separator = " "
result = separator.join(str_list)
print(result)  # 输出:Hello World

3. 使用格式化字符串(fstring)拼接字符串

str1 = "Hello"
str2 = "World"
result = f"{str1} {str2}"
print(result)  # 输出:Hello World

4. 使用字符串格式化(%)拼接字符串

str1 = "Hello"
str2 = "World"
result = "%s %s" % (str1, str2)
print(result)  # 输出:Hello World

5. 使用字符串格式化(format())拼接字符串

str1 = "Hello"
str2 = "World"
result = "{} {}".format(str1, str2)
print(result)  # 输出:Hello World
版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门