温馨提示×

python字符串占位符替换怎么实现

小亿
277
2023-10-17 04:40:25
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Python中,可以使用两种方法来实现字符串占位符的替换。

方法一:使用百分号占位符

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

输出结果:My name is John and I am 25 years old.

在上面的示例中,%s表示字符串占位符,%d表示整数占位符。使用%后面的括号传入变量值进行替换。

方法二:使用format()方法

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

输出结果:My name is John and I am 25 years old.

在上面的示例中,{}表示占位符,使用format()方法传入变量值进行替换。

这两种方法都可以用于替换字符串中的占位符,你可以根据自己的喜好选择其中一种使用。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:Python中怎么替换字符串中的回车符和换行符

1