欢迎访问宙启技术站
智能推送

Python中用于格式化输出的函数:format()

发布时间:2023-06-30 13:42:35

在Python中,可以使用format()函数来格式化输出。format()函数可以将一个值转换为一个指定格式的字符串。

格式化字符串中可以包含占位符{},用于表示待格式化的值的位置。可以在占位符中使用格式化规则,来指定值的显示方式。

下面是一些常用的格式化规则:

1. 基本用法:通过占位符{}和format()函数传递参数来格式化输出。

   name = "Alice"
   age = 25
   
   print("My name is {} and I am {} years old.".format(name, age))
   

输出:My name is Alice and I am 25 years old.

2. 按顺序指定位置:通过数字索引来指定占位符的位置。

   name = "Bob"
   age = 30
   
   print("My name is {0} and I am {1} years old.".format(name, age))
   

输出:My name is Bob and I am 30 years old.

3. 指定参数名称:通过指定参数名称来指定占位符的位置。

   name = "Charlie"
   age = 35
   
   print("My name is {name} and I am {age} years old.".format(name=name, age=age))
   

输出:My name is Charlie and I am 35 years old.

4. 格式化数字:可以使用格式化规则来控制数字的显示方式,如指定小数位数、千位分隔符等。

   price = 1234.56789
   
   print("The price is {:.2f}".format(price))
   

输出:The price is 1234.57

5. 格式化字符串长度:可以使用格式化规则来控制字符串的长度,并通过对齐方式来填充空白。

   text = "Hello"
   
   print("{}".format(text))  # 默认宽度为0,不填充空白
   print("{:10}".format(text))  # 宽度为10,靠左对齐
   print("{:>10}".format(text))  # 宽度为10,靠右对齐
   print("{:^10}".format(text))  # 宽度为10,居中对齐
   

输出:

Hello

Hello

Hello

Hello

以上是format()函数的一些常见用法,还可以使用其他格式化规则和字符来实现更多的格式化效果。