我会用str.format
,你可以简单地解压缩元组:
args = ("Ram", "good", "boy") print("{} is a {} {}".format(*args)) Ram is a good boy
如果您需要操作原始字符串,请先使用re.sub:
import re "%2 and %1 and %0" args = ("one", "two", "three") print(re.sub(r"%\d+", lambda x: "{"+x.group()[1:]+"}", s).format(*args))
输出:
In [6]: s = "%2 and %1 and %0" In [7]: re.sub(r"%\d+", lambda x: "{"+x.group()[1:]+"}", s).format(*args) Out[7]: 'three and two and one' In [8]: s = "%1 and %0 and %2" In [9]: re.sub(r"%\d+",lambda x: "{"+x.group()[1:]+"}", s).format(*args) Out[9]: 'two and one and three'
%\d+
匹配百分号后跟一个或多个数字,x
lambda中的匹配对象是我们用来.group
从中获取匹配字符串的匹配对象,只是将包含数字字符串的数字切成一个{}
用作占位符str.format
.
重新评论你可以拥有比args更多的占位符,sub获取count
最大替换数量的arg:
s = "%0 is a %1 %2" args = ("Ram", "Good") sub = re.sub(r"%\d+\b", lambda x: "{"+x.group()[1:]+"}", s,count=len(args)).format(*args) print(sub)
输出:
Ram is a Good %2
要为任意顺序工作,需要采取更多逻辑:
s = "%2 is a %1 %0" args = ("Ram", "Good") sub = re.sub(r"%\d+\b", lambda x: "{"+x.group()[1:]+"}" if int(x.group()[1:]) < len(args) else x.group(), s).format(*args) print(sub)
输出:
%2 is a Good Ram
将lambda逻辑移动到函数更好一点:
s = "%2 is a %1 %0" args = ("Ram", "Good") def f(x): g = x.group() return "{"+g[1:]+"}" if int(x.group()[1:]) < len(args) else g sub = re.sub(r"%\d+\b",f, s).format(*args)
如果占位符始终是独立的,则使用split和join:
print(" ".join(["{"+w[1:]+"}" if w[0] == "%" else w for w in s.split(" ")]).format(*args)) three and two and one