目录
- 1、`+`加号
- 2、`join`列表
- 3、`%s`占位符
- 4、`format`方法
- 5、`format_map`方法
- 6、`f-string`模板字符串
- 参考
1、+
加号
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result)
# 输出:Hello World
2、join
列表
str1 = "Hello"
str2 = "World"
result = " ".join([str1, str2])
print(result)
# 输出:Hello World
3、%s
占位符
str1 = "Hello"
str2 = "World"
result = "%s %s" % (str1, str2)
print(result)
# 输出:Hello World
4、format
方法
str1 = "Hello"
str2 = "World"
# 直接写占位符
result = "{} {}".format(str1, str2)
# 位置参数
result = "{0} {1}".format(str1, str2)
# 关键字参数
result = "{arg1} {arg2}".format(arg1=str1, arg2=str2)
print(result)
# 输出:Hello World
5、format_map
方法
str1 = "Hello"
str2 = "World"
data = {
'arg1': str1,
'arg2': str2
}
# 类似 format 的关键字参数
result = "{arg1} {arg2}".format_map(data)
print(result)
# 输出:Hello World
6、f-string
模板字符串
版本要求:Python>=3.6
str1 = "Hello"
str2 = "World"
result = f"{str1} {str2}"
print(result)
# 输出:Hello World
参考