python

python中print()怎样输出带变量的字符串

小樊
138
2024-07-14 15:30:24
栏目: 编程语言

要输出带变量的字符串,可以使用字符串格式化的方式或者字符串拼接的方式。以下是两种方法:

  1. 字符串格式化:
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
  1. 字符串拼接:
name = "Bob"
age = 30
print("My name is " + name + " and I am " + str(age) + " years old.")

在上述例子中,我们使用{}作为占位符,然后通过format()方法将变量传入{}中进行替换。另外一种方法是直接使用加号连接字符串和变量,需要注意的是如果变量是数字类型的话需要通过str()方法将其转换为字符串类型。

0
看了该问题的人还看了