gpt4 book ai didi

python - python2.6中没有索引的字符串格式化

转载 作者:太空狗 更新时间:2023-10-29 17:33:52 24 4
gpt4 key购买 nike

我有数千行具有 python2.7+ 样式字符串格式的 python 代码(例如,{} 中没有索引)

"{} {}".format('foo', 'bar')

我需要在 python2.6 下运行这段代码,需要索引。

我想知道是否有人知道允许 python2.6 运行此代码的无痛方式。如果有一个 from __future__ import blah 解决这个问题就太好了。我没有看到一个。这些方面的东西将是我的第一选择。

遥遥领先的第二个是一些可以自动执行添加索引过程的脚本,至少在明显的情况下是这样:

"{0} {1}".format('foo', 'bar')

最佳答案

它并没有完全保留空格,可能会变得更智能一些,但它至少会在不求助于正则表达式或外部解析器的情况下正确识别 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...

示例输入:

s = "{} {}".format('foo', 'bar')
if something:
do_something('{} {} {}'.format(1, 2, 3))

示例输出(注意略有不确定的空白):

s ="{0} {1}".format ('foo','bar')
if something :
do_something ('{0} {1} {2}'.format (1 ,2 ,3 ))

关于python - python2.6中没有索引的字符串格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20524146/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com