Python Format
Python format()
是一种用于格式化字符串的方法。通过使用{}
作为占位符,可以将其他对象的值插入到字符串中。
使用Format进行字符串插值
使用format()
方法,字符串中的占位符可以被替换为想要输出的对象。例如:
```python
print("Hello, {}!".format("World"))
```
输出结果:
Hello, World!
在上面的例子中,format()
方法中的"World"被替换了占位符{}。
使用Format进行数字格式化
在数字方面,format()
方法可以通过更改字符串中的占位符来格式化数字输出。例如:
print("The price is ${:.2f}".format(99.99))
The price is $99.99
在这个例子中,{:.2f}
的意思是输出一个浮点数保留两位小数。其他的数字格式也可以通过更改占位符进行格式化。
使用Format进行日期格式化
在日期方面,format()
方法可以通过更改字符串中的占位符来格式化日期输出。例如:
from datetime import datetime
now = datetime.now()
print("Today is {}".format(now.strftime("%B %d, %Y")))
Today is February 10, 2022
在这个例子中,%B
意味着输出月份的全名,%d
意味着输出日期,%Y
意味着输出年份。
使用Format进行字典格式化
在字典方面,format()
方法可以通过更改占位符来格式化字典输出。例如:
person = {
"name": "John",
"age": 25,
"country": "USA"
}
print("My name is {name}, I am {age} years old, and I am from {country}.".format(**person))
My name is John, I am 25 years old, and I am from USA.
在这个例子中,**person
将字典键值对作为参数传递给format()
方法,然后占位符{name}、{age}、{country}被替换为相应的值。
使用Format进行列表格式化
在列表方面,format()
方法可以通过更改字符串中的占位符来格式化列表输出。例如:
fruits = ["apple", "banana", "cherry"]
print("My favorite fruits are {}, {}, and {}.".format(*fruits))
My favorite fruits are apple, banana, and cherry.
在这个例子中,*fruits
将列表中的元素作为参数传递给format()
方法,然后占位符{}被替换为相应的值。
Python format()
是一种非常强大和灵活的方法,可以用于格式化不同类型的数据,包括字符串、数字、日期、字典和列表。它可以帮助你以一种可读性更高的方式输出数据。
TAGS
Python, Format, 字符串插值, 数字格式化, 日期格式化, 字典格式化, 列表格式化
网友留言(0)