regex - In Python 2.7, how can i replace 't' with 'top' and 'h' with 'hop' only when 'th' is not visible -
i new here , python want give try! replace 't' 'top' , 'h' 'hop' in sentence , when 'th' not visible because 'th' become 'thop'. example : 'thi hi tea' has become 'thopi hopi topea'. have code:
sentence = str(raw_input('give me sentence ')) start = 0 out = '' while true: = string.find( sentence, 'th', start ) if == -1: sentence = sentence.replace('t', 'top') sentence = sentence.replace('h', 'hop') break out = out + sentence[start:i] + 'thop' start = i+2
but not working...any ideas?
import re str = 'thi hi tea' re.sub(r'(?i)h|t(?!h)', r'\g<0>op', str)
yields
'thopi hopi topea'
to break down,
import re
imports regular expression library use substitution,sub
, function(?i)
makes regex case-insesitivet(?!h)
matches 't' not followed 'h'\g<0>op
replacement string substitutes original text followed"op"
.
Comments
Post a Comment