欢迎访问宙启技术站
智能推送

Python中使用的格式化字符串函数

发布时间:2023-06-30 11:48:03

在Python中,常用的格式化字符串函数有以下几种:

1. 字符串的format函数:

name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))

输出:

My name is Alice and I am 25 years old.

format函数通过花括号{}来指定占位符,然后通过format函数的参数按顺序传入具体的值,实现字符串的格式化。

2. 字符串的f-string:

name = "Bob"
age = 30
print(f"My name is {name} and I am {age} years old.")

输出:

My name is Bob and I am 30 years old.

f-string是Python3.6版本之后引入的新特性,可以在字符串前加上字母"f",在花括号{}内直接引用变量名,实现字符串的格式化。

3. 字符串的%运算符:

name = "Charlie"
age = 35
print("My name is %s and I am %d years old." % (name, age))

输出:

My name is Charlie and I am 35 years old.

%运算符可以在字符串中使用类似于C语言的格式化字符串的方式,通过%s和%d等占位符指定要替换的位置,然后通过%运算符后的元组传入具体的值。

此外,还可以为占位符指定一些格式化的选项。例如:

pi = 3.141592653589793
print("The value of pi is {:.2f}".format(pi))

输出:

The value of pi is 3.14

在format函数中,可以使用{:.2f}指定要保留两位小数。同样的,f-string和%运算符也支持类似的选项设置。

以上就是Python中常用的格式化字符串函数。这些函数在字符串的格式化输出、日志记录、模板生成等方面都有广泛的应用。