0

I have converted the binary result of a URL request into a text string, then attempted to replace the instances of '\r' with '' and '\n' with ' ' using the following code:

newvar = str(oldvar)
newvar.replace('\r', '')
newvar.replace('\n', ' ')

However when the variable newvar is printed to the log and written out to a file it retains the '\r' and '\n'. What am I doing wrong? I'm using the exact syntax suggested and that I had already read online.

Thanks

wattostudios
  • 8,666
  • 13
  • 43
  • 57
gdogg371
  • 3,879
  • 14
  • 63
  • 107

4 Answers4

4

replace doesn't modify the string, as strings are immutable; it creates a new string, which you need to assign:

newvar = newvar.replace('\r, '')
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 1
    do you mean 'newvar = oldvar.replace('\r, '')'? – gdogg371 Mar 17 '14 at 23:29
  • If `oldvar` was already a string, that would also work. – jonrsharpe Mar 17 '14 at 23:30
  • does it matter that I am converting the binary output from concurrent futures into a string? The variable 'data' contains that output and I am using the code 'data2 = (str(data)) data2 = data2.replace('\r', '') data2 = data2.replace('\n', ' ')' but it isnt replacing the desired characters still – gdogg371 Mar 17 '14 at 23:35
0

You need of set var to do it:

newvar = str(oldvar)
newvar = newvar.replace('\r', '')
newvar = newvar.replace('\n', ' ')

Then print:

print newvar
Victor Martins
  • 739
  • 7
  • 21
0

The idea is that you assign the replacements to the already existing variable like that:

newvar = (str(oldvar))
newvar = newvar.replace('\r','')
newvar = newvar.replace('\n','')
Alex Koukoulas
  • 998
  • 1
  • 7
  • 21
0

As with many problems, this boils down to Read The Friendly Manual:

str.replace(old, new [, count])

Return a copy [emphasis mine] of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

This doesn't change the string. It returns a copy of the string, modified.

Community
  • 1
  • 1
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328