在Python中,format() 函数用于格式化字符串。它通过占位符来格式化字符串,并将相应的参数值替换到占位符的位置。下面是详细解释以及示例:
str.format() 语法
template_string.format(arg1, arg2, ..., argN, kwarg1=value1, kwarg2=value2, ...)
template_string:包含占位符的模板字符串。
arg1, arg2, ..., argN:按照位置传递的参数。
kwarg1=value1, kwarg2=value2, ...:按照关键字传递的参数。
占位符
{}:用于表示一个占位符,将被传递给 format() 函数的参数值替换。
{index}:用于表示按照位置传递的参数的占位符。
{key}:用于表示按照关键字传递的参数的占位符。
{:format_spec}:用于表示一个带格式规范的占位符。
示例
无参数传递
text = "Hello, {}!"
formatted_text = text.format("world")
print(formatted_text) # 输出 "Hello, world!"按位置传递参数
text = "I'm learning {} programming language and it's {}."
formatted_text = text.format("Python", "fun")
print(formatted_text) # 输出 "I'm learning Python programming language and it's fun."按关键字传递参数
text = "My name is {name} and I'm {age} years old."
formatted_text = text.format(name="John", age=25)
print(formatted_text) # 输出 "My name is John and I'm 25 years old."使用格式规范
text = "Pi is approximately {:.2f}."
formatted_text = text.format(3.14159)
print(formatted_text) # 输出 "Pi is approximately 3.14."
在这个例子中,:.2f 是格式规范,表示将浮点数保留两位小数。
版权属于:戏人看戏博客网
本文链接:https://day.nb.sb/archives/482.html
若无注明均为戏人看戏原创,转载请注明出处,感谢您的支持!