在Python中,有多种方式可以进行字符串拼接。以下是几种常见的方法:
使用加号(+)运算符:
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # 输出:John Doe
运行结果:
使用逗号(,)将多个字符串作为参数传递给print()函数:
first_name = "John"
last_name = "Doe"
print(first_name, last_name) # 输出:John Doe
运行结果:
使用字符串的format()方法:
first_name = "John"
last_name = "Doe"
full_name = "{} {}".format(first_name, last_name)
print(full_name) # 输出:John Doe
运行结果:
使用f-string(格式化字符串):
first_name = "John"
last_name = "Doe"
full_name = f"{first_name} {last_name}"
print(full_name) # 输出:John Doe
运行结果: