1

Possible Duplicate:
Remove specific characters from a string in python

there's a text:"abc\r egf", I need to filter the '\r', however, I think there's some other special characters I need to filter for other text, maybe '\n', so I want to know whether there's a library can do this job?

Community
  • 1
  • 1
user1687717
  • 3,375
  • 7
  • 26
  • 29

1 Answers1

0

As CRUSADER mentioned, standard string replace operations will do what you want, provided you know what characters you want to remove.

text = 'foo\nbar\t\tbaz\r'
new_text = text.replace('\n', '').replace('\t', '').replace('\r', '')
print(new_text)
>>> foobarbaz

See the documentation for how the function works.

However, using re.sub can do this as well, and might even be easier to replace a long list of characters.

import re
text = 'foo\nbar\t\tbaz\r'
chars = '[\n\t\r]'
new_text = re.sub(chars, '', text)
print(new_text)
>>> foobarbaz
Community
  • 1
  • 1
Volatility
  • 31,232
  • 10
  • 80
  • 89