我需要从字符串中删除所有特殊字符,标点符号和空格,以便我只有字母和数字。
当前回答
s = re.sub(r"[-()\"#/@;:<>{}`+=~|.!?,]", "", s)
其他回答
假设你想要使用正则表达式并且你想要/需要unicode - cognant 2。X代码是2to3-ready:
>>> import re
>>> rx = re.compile(u'[\W_]+', re.UNICODE)
>>> data = u''.join(unichr(i) for i in range(256))
>>> rx.sub(u'', data)
u'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\xaa\xb2 [snip] \xfe\xff'
>>>
import re
abc = "askhnl#$%askdjalsdk"
ddd = abc.replace("#$%","")
print (ddd)
你会看到你的结果是
'Askhnlaskdjalsdk
使用翻译:
import string
def clean(instr):
return instr.translate(None, string.punctuation + ' ')
警告:仅适用于ascii字符串。
Python 2 . *
我认为只要filter(str。Isalnum,字符串)工作
In [20]: filter(str.isalnum, 'string with special chars like !,#$% etcs.')
Out[20]: 'stringwithspecialcharslikeetcs'
Python 3。*
在Python3中,filter()函数将返回一个可迭代对象(而不是与上面不同的字符串)。从itertable中获取字符串必须返回连接:
''.join(filter(str.isalnum, string))
或者在连接中传递列表(不确定,但可以快一点)
''.join([*filter(str.isalnum, string)])
注意:unpacking in [*args] valid from Python >= 3.5
function regexFuntion(st) {
const regx = /[^\w\s]/gi; // allow : [a-zA-Z0-9, space]
st = st.replace(regx, ''); // remove all data without [a-zA-Z0-9, space]
st = st.replace(/\s\s+/g, ' '); // remove multiple space
return st;
}
console.log(regexFuntion('$Hello; # -world--78asdf+-===asdflkj******lkjasdfj67;'));
// Output: Hello world78asdfasdflkjlkjasdfj67
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- Printf与std::字符串?
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if