[英]Extract a substring that starts with "http" and ends with ".mp3" from a string
[英]Extract substring that starts and ends with symbol and replace with variable in Python
我试图从 Python 中的字符串中提取一个单词,该字符串的每一侧都用%%
填充,并根据子字符串的值将其替换为变量值。 像这样的东西:
name1 = "Alice"
name2 = "Bob"
date = datetime.datetime.now()
input = "Hi, my name is %%name1%%. Today is %%date%%"
output = ##Find and Replace Line Here
print output
这将导致"Hi, my name is Bob. Today is 2015-10-19 23:07:17.342105"
。
我找到了replace()
方法,我只能找到并用预设值替换整个子字符串,如下所示:
print input.replace("%%name0%%", "name1")
有没有办法在替换之前先提取子字符串的值?
有什么理由不只使用 python 的格式字符串替换?
>>> args = {
... 'name1': "Alice",
... 'name2': "Bob",
... 'date': datetime.datetime.now()
... }
>>> print "Hi, my name is {name1}. Today is {date}".format(**args)
Hi, my name is Alice. Today is 2015-10-20 01:21:36.020427
如果必须使用%%name1%%
您始终可以将%%name1%%
映射到{name1}
并执行上述操作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.