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

format()的实例和应用场景

发布时间:2023-05-19 15:44:43

format()方法是Python中内置的一个字符串格式化函数,可以用来格式化字符串中的变量。这个方法的实例和应用场景非常的广泛,可以用来格式化输出、打印日志、处理数据等等。

常见的format()实例:

1. 字符串格式化输出

可以使用format()来格式化字符串输出,用{}做占位符,然后按照{0}、{1}、{2}的顺序将参数依次填入占位符中。例如:

print("My name is {}. I am {} years old.".format("Tom", 18))

输出结果为:

My name is Tom. I am 18 years old.

2. 字符串格式化输出浮点数

可使用format()方法来格式化输出浮点数,默认情况下是保留6位小数。例如:

x = 3.1415926

print("The pi is {:.2f}".format(x))

输出结果为:

The pi is 3.14

3. 字符串格式化输出数字

可使用format()方法来格式化输出数字,可以控制数字的对齐方式、宽度以及填充字符等。例如:

print("{:<10d} is less than {}".format(3, 4))

输出结果为:

3          is less than 4

"<"表示左对齐,"10"表示宽度为10,"d"表示格式化为整数。如果数字的位数不够,可以使用填充字符填充。例如:

print("{:^10d}".format(123))

输出结果为:

   123    

"^"表示居中对齐,"10"表示宽度为10,"d"表示格式化为整数。

应用场景:

1. 输出日志

日志是一个非常重要的组成部分,使用format()方法来格式化日志信息可以更加方便和易读。例如:

import logging

logging.basicConfig(format='{asctime} {levelname}: {message}', style='{')

logging.error("This is an error message.")

输出结果为:

2021-08-03 15:32:11,335 ERROR: This is an error message.

这里的"{asctime}"和"{levelname}"是占位符,用于指定日志的时间和级别,"{message}"表示实际的日志信息。

2. 处理数据

在处理数据时,format()方法可以用来格式化输出或重新构造数据。例如:

input_str = '1,2,3,4,5'

input_list = input_str.split(',')

new_str = '|'.join('{:^3}'.format(i) for i in input_list)

print(new_str)

输出结果为:

 1  | 2  | 3  | 4  | 5  

这里的split()方法将字符串拆分成一个列表,然后使用format()方法对每个元素进行格式化,最后使用join()方法将格式化后的列表元素用"|"连接起来。

3. 输出表格

在输出表格时,可以使用format()方法来对表格中的数据进行格式化。例如:

table = [['Name', 'Age', 'Gender'],

         ['Tom', 18, 'Male'],

         ['Lucy', 22, 'Female'],

         ['John', 15, 'Male']]

for row in table:

    print('{:<10} {:<5} {:<7}'.format(row[0], row[1], row[2]))

输出结果为:

Name       Age   Gender 

Tom        18    Male   

Lucy       22    Female 

John       15    Male   

这里使用format()方法对每个单元格中的数据进行格式化,保证了表格中的数据对齐和易读。