[英]replace a substring with a non-string value in python
I know we have a replace method to replace a substring within a string with another string.我知道我们有一种替换方法可以用另一个字符串替换一个字符串中的 substring。 But what I want is to replace some substring within a given string with some non-string (could be any data type) values.但我想要的是用一些非字符串(可以是任何数据类型)值替换给定字符串中的一些 substring 。
example -例子 -
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)
Any ideas??有任何想法吗??
Thanks!!谢谢!!
Use str.format
:使用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'
I prefer to use a dict for that because it makes it much more simple to see which argument goes where:我更喜欢为此使用 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)
)
What about this:那这个呢:
string1='My name is %s. My age is %s years. I was born on %s'
print(string1 % ('abc', 40, datetime.date(1980, 1, 1)))
results in:结果是:
'My name is abc. My age is 40 years. I was born on 1980-01-01'
Convert the value to string first:首先将值转换为字符串:
>>> string1.replace("val2", str(val2))
'My name is val1. My age is 40 years. I was born on val3'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.