« Back to Index

[Python State Machine] simple state machine for replacing quotations in a string

View original Gist on GitHub

Tags: #tags: python3, state-machine

state-machine.py

def replace_quotes():
    state = 0
    def state_machine(match):
        nonlocal state
        state = 1 if not state else 0
        return "“" if state else "”"
    return state_machine
    
txt = 'I said "hello mark" but he did not reply so I said "fine then?" and he walked off'

re.sub(r'"', replace_quotes(), txt)

# 'I said “hello mark” but he did not reply so I said “fine then?” and he walked off'