% 格式化
使用百分号(%)操作符,可以指定数据类型和格式。例如:
name = "Tony"
age = 18
salary = 15.2
print("name is %s, age is %d, my salary is %.1f k" % (name, age, salary))
format 方法
使用 `format` 函数,可以动态地插入变量到字符串中。例如:
name = "Tony"
age = 18
salary = 15.2
print("name is {}, age is {}, my salary is {:.1f} k".format(name, age, salary))
f-string 格式化
从Python 3.6开始,可以使用f-string进行格式化,这种方式更加直观和简洁。例如:
name = "Tony"
age = 18
salary = 15.2
print(f"name is {name}, age is {age}, my salary is {salary:.1f} k")
以上三种方法都可以用来格式化输出,选择哪一种取决于你的具体需求和Python的版本。在Python 3.6及以上版本中,f-string通常是首选的格式化方法,因为它提供了更好的可读性和简洁性。