# 方法1:使用加号 (+) 拼接字符串
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # 输出: Hello World
# 方法2:使用 join() 方法拼接字符串
words = ["Python", "is", "fun"]
result = " ".join(words)
print(result) # 输出: Python is fun
# 方法3:使用 f-string (格式化字符串字面量,Python 3.6+)
name = "Alice"
greeting = f"Hello, {name}!"
print(greeting) # 输出: Hello, Alice!
# 方法4:使用 % 操作符(旧式格式化)
age = 25
message = "I am %d years old." % age
print(message) # 输出: I am 25 years old.
# 方法5:使用 format() 方法
template = "Welcome to {}!"
formatted_string = template.format("Python")
print(formatted_string) # 输出: Welcome to Python!
以上代码展示了五种常见的 Python 字符串拼接方法,并附有简单的解释说明。
上一篇:python struct
下一篇:python global用法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站