Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace Space with New Line in Python

Tags:

python

replace

I'm trying to replace '\s' with '\n', but when I print line2, it doesn't print a line with the spaces replaced with new lines. Could anybody indicate what's wrong with my syntax?

for line in fi:
    if searchString in line:
        line2 = line.replace('\s' , '\n') 
        print line2
like image 375
pHorseSpec Avatar asked Dec 14 '22 06:12

pHorseSpec


2 Answers

\s is a Regex token, won't be understood by str.replace.

Do:

line.replace(' ', '\n') 
like image 136
heemayl Avatar answered Dec 16 '22 20:12

heemayl


.replace() replaces strings, you want re.sub(..), e.g.:

for line in fi:
    if searchString in line:
        line2 = re.sub(r'\s' , '\n', line) 
        print line2

The documentation has more details: https://docs.python.org/2/library/re.html#re.sub

like image 26
thebjorn Avatar answered Dec 16 '22 18:12

thebjorn