Python2.7本身已经自带了无类型的位置格式化功能{0}, {1}之类的表示。
但是%本身的格式化串则不支持如 %1$s这样的格式化字符串。手写了一个Python的实现,有空再在Python内核实现之:
#!/usr/bin/python
import re
def lformat(fmt, *args):
newargs = []
def replacepos(match):
escnt = 0;
posstr = match.group()
for c in posstr:
if c == '%':
escnt = escnt + 1
else:
break
if escnt % 2 != 0:
pos = int(posstr[escnt:-1])
newargs.append(args[pos-1])
return posstr[0:escnt]
else:
return posstr
reobj = re.compile(r"[%][1-9]+[0-9]?\$")
result, number = reobj.subn(replacepos, fmt)
if len(newargs)>0:
return result%tuple(newargs)
else:
return fmt%args
testcount = 100000
while testcount > 0:
lformat("%10$d,%9$d,%8$d,%7$d,%6$d,%5$d,%4$d,%3$d,%2$d,%1$d", 1,2,3,4,5,6,7,8,9,10,11)
testcount = testcount - 1
lamda表达式用起来真方便,C++11最近也支持了,很好很好很强大