How can you print strings and variables in Python?

In Python, you can use the print() function to output strings and variables.

Print the string:

print("Hello, World!")  # 直接打印字符串

Print variable.

name = "Alice"
print(name)  # 打印变量name的值

Combine strings and variables for printing.

age = 20
print("My name is", name, "and I am", age, "years old.")  # 打印字符串和变量的组合

Variables can also be printed using string formatting.

name = "Bob"
age = 25
print("My name is %s and I am %d years old." % (name, age))  # 使用字符串格式化打印变量

You can also use f-strings (formatted string literals) to print variables.

name = "Charlie"
age = 30
print(f"My name is {name} and I am {age} years old.")  # 使用f字符串打印变量

These are some common methods for printing strings and variables in Python.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds