python print函数进行格式化输出

在Python中,可以使用print函数进行格式化输出。下面是几种常见的格式化输出方法:

1、使用占位符:
字符串占位符:%s:用于字符串类型的数据
整数占位符:%d:用于整数类型的数据
浮点数占位符:%f:用于浮点数类型的数据
例如:

name = "John"
age = 25
height = 1.75
print("My name is %s, I'm %d years old and %.2f meters tall." % (name, age, height))

2、使用格式化字符串字面值(f-string):
在字符串前添加字母"f",然后用花括号{}表示占位符,可以直接在花括号中填入变量名或表达式。
例如:

name = "John"
age = 25
height = 1.75
print(f"My name is {name}, I'm {age} years old and {height:.2f} meters tall.")

3、使用format方法:
在字符串中使用{}作为占位符,然后调用format方法,按顺序传入要插入的值。
例如:

name = "John"
age = 25
height = 1.75
print("My name is {}, I'm {} years old and {:.2f} meters tall.".format(name, age, height))

posted @ 2024-03-12 09:50  挖坑达人  阅读(106)  评论(0)    收藏  举报