Reputation: 1274
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
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
Reputation: 42017
\s
is a Regex token, won't be understood by str.replace
.
Do:
line.replace(' ', '\n')
Upvotes: 9