Python format()函数的用法是什么

   2025-02-18 7610
核心提示:Python的format()函数是用来格式化字符串的方法。它可以在字符串中插入变量、常量或表达式,并指定它们的格式。format()函数的基

Python的format()函数是用来格式化字符串的方法。它可以在字符串中插入变量、常量或表达式,并指定它们的格式。format()函数的基本用法是通过花括号{}来表示要插入的值的位置,然后使用format()函数来将这些值插入到字符串中。

下面是format()函数的用法示例:

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

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

通过索引指定位置参数:
print("My name is {0} and I am {1} years old.".format(name, age))

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

关键字参数:
print("My name is {name} and I am {age} years old.".format(name="Bob", age=30))

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

使用格式化选项:
pi = 3.14159print("The value of pi is {:.2f}".format(pi))

输出:The value of pi is 3.14

使用索引和格式化选项:
print("My name is {0:10} and I am {1:03d} years old.".format("Alice", 5))

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

format()函数可以根据数据类型自动选择格式化选项,如浮点数的精度、整数的进制等。使用format()函数可以实现复杂的字符串格式化需求,并提高代码的可读性。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言