我知道我们有一个替换方法用另一个字符串替换字符串中的子字符串。但我想要的是用一些非字符串(可能是任何数据类型)值替换给定字符串中的一些子字符串。
示例 -
string1='My name is val1. My age is val2 years. I was born on val3'
val1='abc'
val2=40
val3= datetime.date(1980, 1, 1)
任何想法??
谢谢!
答案 0 :(得分:5)
使用str.format
:
>>> string1 = 'My name is {0}. My age is {1} years. I was born on {2}'
>>> string1.format('abc', 40, datetime.date(1980, 1, 1))
'My name is abc. My age is 40 years. I was born on 1980-01-01'
答案 1 :(得分:4)
我更喜欢使用dict,因为它可以更简单地看到哪个参数在哪里:
'My name is {val1}. My age is {val2} years. I was born on {val3}'.format(
val1 = 'abc',
val2 = 40,
val3 = datetime.date(1980, 1, 1)
)
答案 2 :(得分:3)
这个怎么样:
string1='My name is %s. My age is %s years. I was born on %s'
print(string1 % ('abc', 40, datetime.date(1980, 1, 1)))
结果:
'My name is abc. My age is 40 years. I was born on 1980-01-01'
答案 3 :(得分:0)
首先将值转换为字符串:
>>> string1.replace("val2", str(val2))
'My name is val1. My age is 40 years. I was born on val3'