介绍
Python是一个广受欢迎的编程语言,它非常强大且易用。在Python中,print()函数可以将字符串、数字和其他对象输出到控制台,也是最常用的调试工具之一。本教程将详细介绍Python中print函数的格式化用法。
格式化字符串
在Python中,使用占位符%s可以格式化字符串。当使用%s时,Python会将%s替换为后面传递给print()函数的值。下面是一个例子:
print("Hello, %s" % "world")
这里,%s代表字符串,第二个参数是%s代表的值。输出结果是:
Hello, world
在这个例子中,我们在字符串中使用了%s占位符,并在输出时使用了它,Python会将字符串中的%s替换为后面传递的值。
格式化数字
在Python中,使用格式化字符串可以将数字格式化为指定的样式。以下是一些常见的格式化选项:
- %d – 整数
- %f – 浮点数
- %e – 科学计数法
以下是一些例子:
print("My age is %d" % 25) print("The price is %f" % 9.99) print("The number is %e" % 10000)
输出结果:
My age is 25 The price is 9.990000 The number is 1.000000e+04
在这个例子中,我们用了%d,%f和%e占位符将数字格式化为指定的样式,并在输出时使用了它们。
格式化多个值
在Python中,可以使用一个元组传递多个值,然后使用多个占位符将它们格式化到字符串中。以下是一个例子:
name = "Alice" age = 25 print("My name is %s and I am %d years old" % (name, age))
输出结果:
My name is Alice and I am 25 years old
在这个例子中,我们用一个元组将多个值传递给print()函数,并在字符串中使用了%s和%d占位符,以将它们格式化。
使用格式化字符串方法
在Python 3.6引入了新的格式化字符串方法。 在这种方法中,可以使用大括号{}来占位符,并在字符串前加上f字符,以指示Python使用格式化字符串。以下是一个例子:
name = "Bob" age = 30 print(f"My name is {name} and I am {age} years old")
输出结果:
My name is Bob and I am 30 years old
在这个例子中,我们用了f字符来指示Python使用格式化字符串方法。这种方法也可以使用多个变量:
width = 10 height = 5 print(f"The rectangle has dimensions {width} x {height}")
输出结果:
The rectangle has dimensions 10 x 5
小标题
-
格式化字符串
-
格式化数字
-
格式化多个值
-
使用格式化字符串方法
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/199438.html