共计 433 个字符,预计需要花费 2 分钟才能阅读完成。
format()函数可以用来格式化字符串中的变量。以下是使用 format()函数的基本语法:
# 使用位置参数
print("Hello, {}!".format("World"))
# 使用关键字参数
print("My name is {name} and I am {age} years old.".format(name="Alice", age=30))
# 使用位置参数和关键字参数混合
print("Today is {0:%Y-%m-%d %H:%M:%S}".format(datetime.datetime.now()))
format()函数中的大括号 {} 会被替换为传入的参数值??梢允褂梦恢貌问⒐丶植问蚧旌鲜褂昧秸摺T诖罄ê胖谢箍梢蕴砑痈袷交∠睿?{0:.2f} 表示保留两位小数。
除了上述基本用法,format()函数还支持更多高级用法,如使用索引、填充字符、对齐方式等??梢圆榭?Python 官方文档中的 format()函数说明来了解更多用法。
丸趣 TV 网 – 提供最优质的资源集合!
正文完