Return the string obtained by replacing the leftmost non-overlapping
occurrences of pattern in string by the replacement repl. If the
pattern isn’t found, string is returned unchanged. repl can be a
string or a function; if it is a string, any backslash escapes in it
are processed.
一线解决方案:
简短说明:
'@@@'
字符串替换为python字符串格式标识符'{}'
。len(kv)
将替换的数量减少到dict的长度,当dict的元素少于字符串中的'@@@'
时,避免{kv.values()
提取字典值*kv.values()
解压字典值,并将其作为参数传递给stringformat
方法。在示例代码执行:
^{pr2}$输入
和输出
此解决方案的优点: 没有显式循环(显式循环在python中几乎总是一个坏主意),只有一行代码。此外,当
'@@@'
中的'@@@'
的数目小于**或大于kv
**中的值数目时,当str.replace
中的count
参数被指定时,也起作用。在这导致了我的解决方案的最终和99%故障保护变体,使用dict的中的
len
作为^{count
参数:这是一种使用
str.replace
和可选参数count
的方法。在例如:
MoreInfo
您可以使用
re.sub
完成任何排序输出
^{pr2}$相关问题 更多 >
编程相关推荐