【问题标题】:Remove special characters from the string [closed]从字符串中删除特殊字符[关闭]
【发布时间】:2013-01-10 11:13:06
【问题描述】:

在下面的字符串中如何去掉所有的特殊字符

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"

【问题讨论】:

  • 什么叫“特殊字符”?
  • "所有字符都是特殊的。" - 汤姆克里斯蒂安森
  • :) 我的意思是要删除的字符是 \x021\x05.......
  • 那里的1 怎么样?\x02 是一个字符,\x05 也是一个字符,而两者之间还有一个1。

标签: python


【解决方案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 个为非打印字符,此范围包括 return 、backspace 等,32-127 是可打印的 ASCII 字符。

128-255: 扩展 ASCII

ord() 返回单个字符的整数值,我们可以通过31 &lt; ord(x) &lt;127 对其进行过滤。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-04-11
  • 2016-01-23
  • 2019-11-09
  • 2011-08-29
相关资源
最近更新 更多