猿问

在某些字符周围填充

例如,我有这个字典:

dict = { "(": " ( ", ")": " ) " ... }

我有字符串,例如:"if (x < 0) {" 我希望它是"if ( x < 0 ) {"

有什么方法可以做到?(使用字典并不重要,重要的是在某些字符周围添加填充)


斯蒂芬大帝
浏览 190回答 2
2回答

一只斗牛犬

如果您想在填充已经存在的情况下避免双空格(如您的示例中所示),您可以使用正则表达式,使用前瞻和后视查找需要填充的字符前面(?<=...)或后面(?=...)的位置非空格性格\S:>>> padding = "()">>> p = r"(?<=\S)(?=[{0}])|(?<=[{0}])(?=\S)".format(padding)>>> re.findall(p, text)['', '']>>> re.sub(p, " ", text)'if ( x < 0 ) {'

Cats萌萌

尝试使用str.replace:def pad(s):&nbsp; &nbsp; for k, v in dictionary.items():&nbsp; &nbsp; &nbsp; &nbsp; s = s.replace(k, v)&nbsp; &nbsp; return s>>> dictionary = { "(": " ( ", ")": " ) "}>>> pad("if (x < 0) {")'if&nbsp; ( x < 0 )&nbsp; {'
随时随地看视频慕课网APP

相关分类

Python
我要回答