pHorseSpec
pHorseSpec

Reputation: 1274

Replace Space with New Line in Python

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

Upvotes: 5

Views: 24927

Answers (2)

thebjorn
thebjorn

Reputation: 27311

.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

Upvotes: 5

heemayl
heemayl

Reputation: 42017

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

Do:

line.replace(' ', '\n') 

Upvotes: 9

Related Questions