This one works with nested quotes, although it does not handle your edge cases
def quote(string):
text = ''
stack = []
for token in iter_tokes(string):
if is_quote(token):
if stack and stack[-1] == token: # closing
text += '}'
stack.pop()
else: # opening
text += '\\quotation{'
stack.append(token)
else:
text += token
return text
def iter_tokes(string):
i = find_quote(string)
if i is None:
yield string
else:
if i > 0:
yield string[:i]
yield string[i]
for q in iter_tokes(string[i+1:]):
yield q
def find_quote(string):
for i, char in enumerate(string):
if is_quote(char):
return i
return None
def is_quote(char):
return char in '\'\"'
def main():
quoted = None
with open('input.txt') as fh:
quoted = quote(fh.read())
print quoted
main()