![](/img/trans.png)
[英]Single or Multiple { (curly brackets) in Python for formatting an string
[英]Convert a string with curly brackets using python
我有以下字符串:
{At condition {0}, the value of {1} must be between {2} and {3}.}{{code{min <= 100}}}{{code{min}}}{0}{100}
如何在 python 中将任何类似的字符串转换为以下格式?
At condition `min <= 100`, the value of `min` must be between 0 and 100.
大括号中的数字应替换为相应的值。 如果将值包装到{code{value}}
中,则应添加专用符号 ``。
好吧,这有点脆弱/混乱,但考虑到您提供的结构,它应该可以工作。
def convert(s):
# Find index of first }{ as this is end of initial string
idx = s.find('}{')
initial = s[1:idx]
# Everything after this index is an argument
args = s[idx+2:-1]
args = args.split('}{')
# Iterate through args and subsitute into initial string
for i, arg in enumerate(args):
# Check to see if arg wrapped in {code{}}
val_idx = arg.find('code{')
if val_idx != -1:
# Replace wrapped value with backticks
arg = '`{}`'.format(arg[val_idx+5:-2])
# Place arg into proper place in initial string
initial = initial.replace('{{{}}}'.format(i), arg)
return initial
来电:
convert('{At condition {0}, the value of {1} must be between {2} and {3}.}{{code{min <= 100}}}{{code{min}}}{0}{100}')
convert('{{0} bar}{foo}')
回报:
At condition `min <= 100`, the value of `min` must be between 0 and 100.
foo bar
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.