温馨提示×

python怎么打印变量和字符串

小亿
103
2024-04-11 14:32:04
栏目: 编程语言

在Python中,可以使用print()函数来打印变量和字符串。

要打印一个变量,只需将变量名放在print()函数的括号内即可,例如:

x = 10
print(x)

要同时打印变量和字符串,可以使用逗号将它们分开,例如:

name = "Alice"
age = 25
print("My name is", name, "and I am", age, "years old.")

另一种方法是使用字符串的格式化功能,可以使用占位符来代替变量,然后使用.format()方法将变量填充到字符串中,例如:

name = "Bob"
age = 30
print("My name is {} and I am {} years old.".format(name, age))

或者使用f-string(格式化字符串字面值),在字符串前加上字母"f",然后在字符串中使用大括号{}来包裹变量名,例如:

name = "Charlie"
age = 35
print(f"My name is {name} and I am {age} years old.")

以上是几种常用的打印变量和字符串的方法,可以根据具体情况选择适合的方法。

0