Python函数应用举例:字符串格式化
发布时间:2023-10-08 12:24:25
字符串格式化是将变量插入到字符串中,以便动态生成需要的输出。在Python中,字符串格式化有多种方法,其中最常用的方法是使用字符串的format()方法和f-strings。
下面是一些使用字符串格式化的例子:
1. 使用format()方法:
name = "Alice"
age = 25
print("My name is {} and I'm {} years old.".format(name, age))
输出:My name is Alice and I'm 25 years old.
2. 使用f-strings(格式化字符串字面值):
name = "Bob"
age = 30
print(f"My name is {name} and I'm {age} years old.")
输出:My name is Bob and I'm 30 years old.
3. 格式化数字:
n = 3.14159
print("The value of π is {:.2f}".format(n))
输出:The value of π is 3.14
4. 格式化布尔值:
is_true = True
is_false = False
print("The value of is_true is {} and is_false is {}".format(is_true, is_false))
输出:The value of is_true is True and is_false is False
5. 格式化日期和时间:
import datetime
today = datetime.date.today()
time = datetime.datetime.now().time()
print("Today is {:%Y-%m-%d} and the current time is {:%H:%M:%S}".format(today, time))
输出:Today is 2021-08-20 and the current time is 15:30:00
6. 格式化列表和元组:
fruits = ['apple', 'banana', 'orange']
print("I like {}, {} and {}.".format(*fruits))
numbers = (1, 2, 3)
print("The numbers are {}, {} and {}.".format(*numbers))
输出:I like apple, banana and orange. 和 The numbers are 1, 2 and 3.
这些只是字符串格式化的一部分应用举例。Python的字符串格式化非常强大和灵活,可以根据具体的需求进行更复杂的格式化操作。
