我需要从字符串中删除所有特殊字符,标点符号和空格,以便我只有字母和数字。


当前回答

字符串。标点符号包含以下字符:

'!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~'

可以使用translate和maketrans函数将标点符号映射为空值(替换)

import string

'This, is. A test!'.translate(str.maketrans('', '', string.punctuation))

输出:

'This is A test'

其他回答

import re
abc = "askhnl#$%askdjalsdk"
ddd = abc.replace("#$%","")
print (ddd)

你会看到你的结果是

'Askhnlaskdjalsdk

较短的方法:

import re
cleanString = re.sub('\W+','', string )

如果你想在单词和数字之间有空格,用''代替''

这将删除除空格外的所有非字母数字字符。

string = "Special $#! characters   spaces 888323"
''.join(e for e in string if (e.isalnum() or e.isspace()))

特殊字符空格888323

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
s = re.sub(r"[-()\"#/@;:<>{}`+=~|.!?,]", "", s)