从字符串中删除特殊字符

时间:2013-01-10 11:13:06

标签: python

在以下字符串中如何删除所有特殊字符

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"

1 个答案:

答案 0 :(得分:1)

使用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'

前32个是非打印字符,此范围包括returnbackspace等,32-127是可打印的ASCII字符。

128-255:扩展ASCII

ord()为单个字符返回此整数值,我们可以按31 < ord(x) <127对其进行过滤。

enter image description here