如何将%s变成{0},{1}…不太笨重?

问题描述 投票:5回答:6

我必须将一个包含占位符的字符串用于以后的替换,例如:

"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解决方案会是什么样?

澄清更新:

  • 生成的字符串未在python中使用。我do那里需要计数器编号! (因此{}不够好!)!
  • 我只需要关心%s字符串,因为保证消息仅使用%s(什么也不使用%i %f
python python-3.x
6个回答
5
投票

使用带有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


0
投票

使用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}

0
投票

我会按照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

0
投票

我认为应该工作

rv.replace('%s','{{{}}}').format(*range(rv.count('%s')))


-1
投票

可以这样做:rv.replace('%s', '{}')

您不必使用数字,如果这里有%s,则该数字在此处多余


-3
投票

您尝试使用.format吗?

string.format(0 =值,1 =值)

所以:

"A {0} B {1}".format(0=value, 1=value)

© www.soinside.com 2019 - 2024. All rights reserved.