温馨提示×

python format函数的功能有哪些

小亿
106
2023-12-26 20:34:16
栏目: 编程语言

Python的format()函数有以下功能:

  1. 格式化字符串:可以使用花括号 {} 在字符串中指定占位符,然后使用 format() 函数来替换占位符为指定的值。 例如:‘Hello, {}!’.format(‘Python’) 将会返回 ‘Hello, Python!’。

  2. 格式化数字:可以使用花括号 {} 在字符串中指定格式化的方式来显示数字。 例如:‘The value is {:.2f}’.format(3.14159) 将会返回 ‘The value is 3.14’。

  3. 格式化日期和时间:可以使用花括号 {} 在字符串中指定格式化的方式来显示日期和时间。 例如:‘Today is {:%Y-%m-%d}’.format(datetime.datetime.now()) 将会返回 ‘Today is 2021-01-01’。

  4. 格式化字典:可以使用花括号 {} 在字符串中指定字典中的键来替换为对应的值。 例如:‘My name is {name} and I am {age} years old.’.format(name=‘Alice’, age=25) 将会返回 ‘My name is Alice and I am 25 years old.’。

  5. 格式化列表和元组:可以使用花括号 {} 在字符串中指定列表或元组中的索引来替换为对应的值。 例如:‘The first element is {} and the second element is {}.’.format(my_list[0], my_tuple[1])。

  6. 格式化对象:可以使用花括号 {} 在字符串中指定对象的属性来替换为对应的值。 例如:‘The name is {obj.name} and the age is {obj.age}.’.format(obj=my_object)。

0