【发布时间】:2019-06-19 16:07:33
【问题描述】:
我的字符串格式如下:
string = "{part1}_{part2}_{part3}"
我想通过将不同的部分设置为不同的值来格式化字符串。 问题是第 2 部分是可选的。所以我不能执行以下操作,因为它会给我留下重复的下划线:
result = string.format(part1="A", part2="", part3="B")
actual_result = "A__B"
desired_result = "A_B"
我不能用单个下划线替换所有重复的下划线,因为我用来替换部分的字符串可能已经包含重复的下划线:
result = string.format(part1="A__A", part2="", part3="B__B")
result = result.replace("__", "_")
actual_result = "A_A_B_B"
desired_result = "A__A_B__B"
我的解决方案看起来像这样,但我想知道是否有更优雅的东西。
ignore_str = "$IGNORE_STRING$"
string = "{part1}_{part2}_{part3}"
result = string.format(part1="A__A", part2=ignore_str, part3="B__B")
result = result.replace("_" + ignore_str, "")
actual_result = "A__A_B__B"
我有点希望有一个很酷的str.format() 技巧可以应用。我知道我可以编写自己的格式类,但这似乎会产生更多代码,并且可能会让读者感到困惑。
我正在寻找一种 Python 风格、优雅且易读的解决方案。
【问题讨论】:
-
我认为只有
.format()无法做到这一点。你可以想出你自己的模板语言来解析和替换。