# 示例代码:Python 拼接字符串和变量
# 方法1:使用加号 (+) 拼接字符串和变量
name = "Alice"
greeting = "Hello, " + name
print(greeting) # 输出: Hello, Alice
# 方法2:使用格式化字符串 (f-string),这是 Python 3.6+ 的特性
age = 30
info = f"My name is {name} and I am {age} years old."
print(info) # 输出: My name is Alice and I am 30 years old.
# 方法3:使用 str.format() 方法
template = "Welcome, {}. You are {} years old."
message = template.format(name, age)
print(message) # 输出: Welcome, Alice. You are 30 years old.
# 方法4:使用 % 操作符(旧式格式化)
welcome = "Hi, %s. How are you at age %d?" % (name, age)
print(welcome) # 输出: Hi, Alice. How are you at age 30?
+
可以将多个字符串或字符串与变量拼接在一起。f
或 F
,可以在大括号 {}
中直接写变量名或表达式,方便且高效。{}
和 .format()
方法来插入变量值,适合复杂的格式化需求。上一篇:python两个字典合并
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站