返回列表 发帖

[问题求助] Python删除问号开始后面的全部字符错在哪里?

#!/usr/bin/python
import re
str = "this is string ?example....wow!!! this is really string";
print re.sub(r'^?.','',str);COPY
我想删除?开始后面的全部字符,用正则的方法,
报错无法运行。

回复 1# netdzb
import re
str = "this is string ? example....wow!!! this is really string"
print re.sub(r'(?<=[?|?]).+','',str)COPY
测试中发现,你的问号是中文的,顺手做了一个中文匹配,不过有点bug
真心不喜欢你的代码风格。。。

TOP

回复 2# wujunkai

我刚才发的新问题,好像就是要做个中文字符的判断。该如何修改?
谢谢!

TOP

回复 3# netdzb
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import re
str = "this is string ?example....wow!!! this is really string"
str = re.sub(r'(?<=[?|?]).+','',str)
if str[-1]!='?' :
    str=str[:-1]+'?'
print strCOPY
不要总想着一行搞定,该多写点还是要写的。

TOP

返回列表