ITPub博客

首页 > 数据库 > 数据库开发技术 > 快速了解Python中format函数的使用

快速了解Python中format函数的使用

原创 数据库开发技术 作者:derekwh 时间:2024-04-17 11:26:26 0 删除 编辑

Python中的format()函数是一个内置函数,用于格式化字符串。它通过替换字符串中的占位符{}来插入指定的值。这个函数的语法如下:

str.format(*args, **kwargs)

其中,*args是可选参数,表示一个或多个要插入的值,**kwargs也是可选参数,表示一个或多个要插入的键值对。


下面是一些使用format()函数的例子:

无参数


s = "Hello, {}!"
print(s.format("world"))  # 输出:Hello, world!

位置参数

s = "I am {} years old and my name is {}."
print(s.format(25, "John"))  # 输出:I am 25 years old and my name is John.

关键字参数

s = "My name is {name} and I am {age} years old."
print(s.format(name="John", age=25))  # 输出:My name is John and I am 25 years old.

混合使用位置参数和关键字参数

s = "My name is {name} and I am {0} years old."
print(s.format(25, name="John"))  # 输出:My name is John and I am 25 years old.

使用字典作为关键字参数

person = {"name": "John", "age": 25}
s = "My name is {name} and I am {age} years old."
print(s.format(**person))  # 输出:My name is John and I am 25 years old.

使用索引

s = "The {2} of {0} is {1:.2f}"
print(s.format("pi", 3.14159, "circle"))  # 输出:The circle of pi is 3.14

其他案例

为了大家更清晰的熟悉format的使用,再给出一些案例。

print(format(2918))
print(format(0x500, 'X'))
print(format(3.14, '0=10'))
print(format(3.14159, '05.3'))
print(format(3.14159, 'E'))
print(format('test', '<20'))
print(format('test', '>20'))
print(format('test', '^20'))
2918
500
0000003.14
03.14
3.141590E+00
test                
                test
        test 

以上就是Python中format()函数的基本使用方法,通过这个函数,我们可以很方便地在字符串中插入各种值,使得字符串的内容更加丰富和灵活。

原文作者:Python学习杂记;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论
央企算法工程师,微信公众号: python数智工坊

注册时间:2021-03-14

  • 博文量
    305
  • 访问量
    162348