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-insesitive
  • t(?!h) matches 't' not followed 'h'
  • \g<0>op replacement string substitutes original text followed "op".

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -