我必须将一个包含占位符的字符串用于以后的替换,例如:
"A %s B %s"
并将其转换为:
"A {0} B {1}"
我想出了:
def _fix_substitution_parms(raw_message):
rv = raw_message
counter = 0
while '%s' in rv:
rv = rv.replace('%s', '{' + str(counter) + '}', 1)
counter = counter + 1
return rv
可以,但是感觉很笨拙,根本不是“惯用的” python。
一个很好的,惯用的python解决方案会是什么样?
澄清更新:
{}
不够好!)! %s
字符串,因为保证消息仅使用%s
(什么也不使用%i %f
)使用带有lambda函数的re.sub
对每个元素重新应用一次替换,并使用itertools.count
来顺序获取数字:
import itertools
import re
s = "A %s B %s"
counter = itertools.count()
result = re.sub('%s', lambda x: f'{{{next(counter)}}}', s)
print(result) # 'A {0} B {1}'
请记住将其包装在函数中以多次执行此操作,因为您需要刷新itertools.count
。
使用re.sub
进行动态替换:
import re
text = "A %s B %s %s B %s"
def _fix_substitution_parms(raw_message):
counter = 0
def replace(_):
nonlocal counter
counter += 1
return '{{{}}}'.format(counter - 1)
return re.sub('%s', replace, raw_message)
print(_fix_substitution_parms(text)) # A {0} B {1} {2} B {3}
我会按照Reznik originally的建议进行操作,然后在该位置上调用.format
:
def _fix_substitution_parms(raw_message: str) -> str:
num_to_replace = raw_message.count("%s")
python_format_string_message = raw_message.replace("%s", "{{{}}}")
final_message = python_format_string_message.format(*range(num_to_replace))
return final_message
我认为应该工作
rv.replace('%s','{{{}}}').format(*range(rv.count('%s')))
可以这样做:rv.replace('%s', '{}')
您不必使用数字,如果这里有%s
,则该数字在此处多余
您尝试使用.format吗?
string.format(0 =值,1 =值)
所以:
"A {0} B {1}".format(0=value, 1=value)