0

In the following string how to remove all the special characters

str1="0Cell Phones: Smartphone,\x02\x05\x0e\x02\x05Mobile Phone - Best Buy13AT&T Wireless: AT&T Phones & Cell Phone Plans - Best Buy4\x02\x05\x0e\x02\x05Cell Phones: Smartphone, Mobile Phone - Best Buy1\x02\x05\x0e\x02\x05AT&T Wireless: AT&T Phones & Cell Phone Plans - Best Buy"
Rajeev
  • 42,191
  • 76
  • 179
  • 280

1 Answers1

2

using ord():

In [35]: str1="0Cell Phones: Smartphone,\x02\x05\x0e\x02\x05Mobile Phone - Best Buy13AT&T Wireless: AT&T Phones & Cell Phone Plans - Best Buy4\x02\x05\x0e\x02\x05Cell Phones: Smartphone, Mobile Phone - Best Buy1\x02\x05\x0e\x02\x05AT&T Wireless: AT&T Phones & Cell Phone Plans - Best Buy"

In [36]: "".join(x for x in str1 if 31 < ord(x) <127)

Out[36]: '0Cell Phones: Smartphone,Mobile Phone - Best Buy13AT&T Wireless: AT&T Phones & Cell Phone Plans - Best Buy4Cell Phones: Smartphone, Mobile Phone - Best Buy1AT&T Wireless: AT&T Phones & Cell Phone Plans - Best Buy'

First 32 are non-printing characters, this range includes return ,backspace etc and 32-127 are the printable ASCII characters.

128-255: extended ASCII

ord() returns this integer value for a single character and we can filter it by 31 < ord(x) <127.

enter image description here

Ashwini Chaudhary
  • 232,417
  • 55
  • 437
  • 487