2

I have a list that looks like this:

['\r1/19/2015', '1/25/2015\r']

I got this data from the web, and it just started coming with the \r today. This causes an error in my script, so I am wondering how to remove the \r from the list.

Bhargav Rao
  • 45,811
  • 27
  • 120
  • 136
iqueqiorio
  • 1,119
  • 2
  • 32
  • 76

3 Answers3

6

You can use str.strip. '\r' is a carriage return, and strip removes leading and trailing whitespace and new line characters.

>>> l = ['\r1/19/2015', '1/25/2015\r']
>>> l = [i.strip() for i in l]
>>> l
['1/19/2015', '1/25/2015']
Cory Kramer
  • 107,498
  • 14
  • 145
  • 201
4

You can use replace also

>>> l = ['\r1/19/2015', '1/25/2015\r']
>>> [i.replace('\r','') for i in l]
['1/19/2015', '1/25/2015']
Bhargav Rao
  • 45,811
  • 27
  • 120
  • 136
2

If for some reason the \r characters are not just at the beginning and/or end of your strings, the following will work:

In [77]: L = ['\r1/19/2015', '1/25/2015\r', '1/23/\r2015']

In [78]: [item.replace("\r", "") for item in L]
Out[78]: ['1/19/2015', '1/25/2015', '1/23/2015']
MattDMo
  • 96,286
  • 20
  • 232
  • 224