Python 否定一个regex-sith-re和sub
我有以下字符串Python 否定一个regex-sith-re和sub,python,regex,Python,Regex,我有以下字符串 t1 = 'hello, how are you ?' 我只想得到这个: t2 = 'hello how are you' 因此,我尝试将sub()from与否定正则表达式一起使用,如下所示: t2 = re.sub(r'^([a-z])','',t1) 但是我没有成功 删除标点符号的最佳方法是什么 谢谢试试这样的方法: re.sub("[^a-zA-Z ]","",'hello, how are you ?').rstrip() rstrip用于除去问号后留下的尾随空格
t1 = 'hello, how are you ?'
我只想得到这个:
t2 = 'hello how are you'
因此,我尝试将sub()from与否定正则表达式一起使用,如下所示:
t2 = re.sub(r'^([a-z])','',t1)
但是我没有成功
删除标点符号的最佳方法是什么
谢谢试试这样的方法:
re.sub("[^a-zA-Z ]","",'hello, how are you ?').rstrip()
rstrip用于除去问号后留下的尾随空格
当然,只有当您真的想使用正则表达式时,才可以这样做。问题中@f43d65链接的任何方法都可能运行良好,速度也可能更快。删除标点符号的最佳方法不使用正则表达式
# Python 3
import string
transmapping = str.maketrans(None, None, string.punctuation)
t1 = 'hello, how are you ?'
t2 = t1.translate(transmapping).strip()
以下是和的Python 3文档
以下是Python2文档(此处未使用)和
使用正则表达式进行字符串转换有点像使用反铲,而prybar可以这样做。它庞大、笨拙,如果你做得不对,很可能会把事情搞砸。假设你只想删除最后一个标点符号,而且它是一个问号: /[\?]$/ 这意味着删除字符串末尾括号中的任何内容。我希望这会有所帮助
# Python 2
import string
t1 = 'hello, how are you ?'
t2 = t1.translate(None, deletechars=string.punctuation).strip()