Cap*_*day 13 python backport string-formatting python-2.6
我有成千上万行的python代码有python2.7 +样式字符串格式化(例如{} s中没有索引)
"{} {}".format('foo', 'bar')
Run Code Online (Sandbox Code Playgroud)
我需要在python2.6下运行此代码,python2.6 需要索引.
我想知道是否有人知道一个无痛的方式允许python2.6运行此代码.如果有一个"来自__future__ import blah"解决问题,那就太棒了.我没有看到一个.这些方面的东西将是我的第一选择.
一个遥远的第二个是一些脚本可以自动化添加索引的过程,至少在明显的情况下:
"{0} {1}".format('foo', 'bar')
Run Code Online (Sandbox Code Playgroud)
它并没有完全保留whitespacing并且可能会变得更聪明,但它至少会正确识别Python字符串(撇号/引号/多行),而无需使用正则表达式或外部解析器:
import tokenize
from itertools import count
import re
with open('your_file') as fin:
output = []
tokens = tokenize.generate_tokens(fin.readline)
for num, val in (token[:2] for token in tokens):
if num == tokenize.STRING:
val = re.sub('{}', lambda L, c=count(): '{{{0}}}'.format(next(c)), val)
output.append((num, val))
print tokenize.untokenize(output) # write to file instead...
Run Code Online (Sandbox Code Playgroud)
输入示例:
s = "{} {}".format('foo', 'bar')
if something:
do_something('{} {} {}'.format(1, 2, 3))
Run Code Online (Sandbox Code Playgroud)
示例输出(稍微注意一下whitespacing):
s ="{0} {1}".format ('foo','bar')
if something :
do_something ('{0} {1} {2}'.format (1 ,2 ,3 ))
Run Code Online (Sandbox Code Playgroud)