change string during pyparsing

家住魔仙堡 提交于 2019-12-04 09:47:16

Karl Knechtel's comment is valid, but if you want to change a matched token, you can do this in a parse action.

def changeText(s,l,t):
    return "boo" + t[0]

expr = Literal("A").setParseAction(changeText) + "B"
print expr.parseString("A B").asList()

Will print:

['booA', 'B']

If you just want to replace an expression with a constant literal string, use replaceWith:

expr = Literal("A").setParseAction(replaceWith("Z")) + "B"
print expr.parseString("A B").asList()

prints:

['Z', 'B']
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!