Python中并没有内置的`printf`函数,它使用`print`函数进行格式化输出。`print`函数允许你通过格式化字符串来输出带有不同数据类型的内容。下面是一些`print`函数的基本用法:
1. 基本输出
print("Hello, World!") 输出字符串
2. 格式化输出
name = "World"
age = 25
print("My name is %s and I am %d years old." % (name, age)) 使用%操作符格式化字符串
3. 输出不同类型的数据
x = 16
y = 10
print("The value of x is %d and the value of y is %d." % (x, y)) %d表示十进制整数
print("The hexadecimal value of x is %x." % x) %x表示十六进制整数
print("The octal value of x is %o." % x) %o表示八进制整数
4. 输出浮点数
pi = math.pi
print("The value of PI is approximately %f." % pi) %f表示浮点数
print("The value of PI with 3 decimal places is %.3f." % pi) 保留3位小数
5. 输出列表和字典
list_values = [1, 2, 3, 4]
dict_values = {'a': 1, 'b': 2, 'c': 3}
print(list_values) 输出列表
print(dict_values) 输出字典
请注意,在Python 3.7及以后的版本中,`print`是一个函数,所以需要使用括号。例如:
print("Hello, World!") 正确
print "Hello, World!" Python 2.x的写法,Python 3.x中会报错