How to automatically change a particular word while writing to a file in python? -


say method returns me long list of lines writing file. on fly there way can change word "bread" "breakfast", assuming word "bread" exists in several places of file being generated.

thanks.

i have assigned sys.stdout file object, way console print goes file. on fly hack great.

you use regular expressions.

import re  word = 'bread' rword = 'breakfast' line = 'this piece of bread' line = re.sub(r'\b{0}\b'.format(re.escape(word)), rword, line) # 'this piece of breakfast' 

the advantage of using regular expressions can detect word boundaries (ie. \b). prevents replacing words contain word (ie. breadth).

you line line, or replace word in whole document @ once.


Comments

Popular posts from this blog

java - pagination of xlsx file to XSSFworkbook using apache POI -

Unlimited choices in BASH case statement -

apache - How do I stop my index.php being run twice for every user -