python format()函数的使用技巧

   2024-10-01 3790
核心提示:替换字符串中的占位符:name = Aliceage = 30message = My name is {} and I am {} years old..format(name, age)print(message)

替换字符串中的占位符:

name = "Alice"age = 30message = "My name is {} and I am {} years old.".format(name, age)print(message)
指定占位符的顺序:
name = "Alice"age = 30message = "My name is {1} and I am {0} years old.".format(age, name)print(message)
格式化数字的显示:
num = 123.456789formatted_num = "{:.2f}".format(num)print(formatted_num)  # 输出:123.46
格式化日期时间:
from datetime import datetimenow = datetime.now()formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")print(formatted_date)
使用键值对替换占位符:
person = {"name": "Alice", "age": 30}message = "My name is {name} and I am {age} years old.".format(**person)print(message)
使用列表替换占位符:
itEMS = ["apple", "banana", "cherry"]message = "I like {} and {} and {}.".format(*items)print(message)

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号