Replace function in pyPEG

128 views Asked by At

How can i replace some words in pyPEG? For example i have sentence

John plays football

I want replace John to Bob and compose it to:

Bob plays footbal.

from pypeg2 import *

class Try(str):

    grammar = 'John ', restline

    # I am think that here should be same callback function, but i have no idea how to type it

f = parse("John plays football", Try)

print(compose(f))

OUTPUT:

John plays football
1

There are 1 answers

7
Adi219 On

"John" is the first parameter which is being replaced and "Bob" is the replacement string.

Use .replace(something, with_something_else).

from pypeg2 import *

def Try(String):

    grammar = 'John'
    String = String.replace(grammar, 'Bob')
    return String

f = Try("John plays football")

print(f)

Output:

"Bob plays football"