如何去除字符串开头或结尾的非字母数字字符
我有一个列表,里面的每个字符串开头或结尾都有一些多余的字符,这些字符不是字母也不是数字。
比如:
'cats--'
我想去掉这些多余的字符,比如 --。
我试过:
for i in thelist:
newlist.append(i.strip('\W'))
但是这样没成功。有没有什么建议?
5 个回答
0
使用strip的时候,你需要知道要去掉的子字符串是什么。
>>> 'cats--'.strip('-')
'cats'
你可以用re
模块来去掉那些不是字母或数字的字符,但我觉得这就像用大炮打老鼠一样不合适。用str.isalpha()
可以检查字符串中是否包含字母,所以你只需要保留那些字母:
>>> ''.join(char for char in '#!cats-%' if char.isalpha())
'cats'
>>> thelist = ['cats5--', '#!cats-%', '--the#!cats-%', '--5cats-%', '--5!cats-%']
>>> [''.join(c for c in e if c.isalpha()) for e in thelist]
['cats', 'cats', 'thecats', 'cats', 'cats']
你想去掉非字母和数字的字符,所以我们可以把这个做得更好:
>>> [''.join(c for c in e if c.isalnum()) for e in thelist]
['cats5', 'cats', 'thecats', '5cats', '5cats']
这个方法得到的结果和用re模块得到的结果是完全一样的(参考Christian的回答):
>>> import re
>>> [re.sub("[^\\w]", "", e) for e in thelist]
['cats5', 'cats', 'thecats', '5cats', '5cats']
不过,如果你只想去掉字符串末尾的非字母和数字字符,你应该使用另一种模式,比如这个(查看re文档):
>>> [''.join(re.search('^\W*(.+)(?!\W*$)(.)', e).groups()) for e in thelist]
['cats5', 'cats', 'the#!cats', '5cats', '5!cats']
1
我认为这是最简短的非正则表达式解决方案:
text = "`23`12foo--=+"
while len(text) > 0 and not text[0].isalnum():
text = text[1:]
while len(text) > 0 and not text[-1].isalnum():
text = text[:-1]
print text
2
你可以使用正则表达式。方法 re.sub()
需要三个参数:
- 正则表达式
- 替换的内容
- 要处理的字符串
代码:
import re
s = 'cats--'
output = re.sub("[^\\w]", "", s)
print output
解释:
- 部分
"\\w"
可以匹配任何字母或数字。 [^x]
会匹配任何不是x
的字符。
7
如果你想从字符串的两端去掉一个或多个不是字母、数字和 _
的字符,可以使用下面的代码:
re.sub(r'^\W+|\W+$', '', '??cats--') # => cats
如果你也想去掉 _
,那么可以把 \W
放进一个字符类中,并在里面加上 _
:
re.sub(r'^[\W_]+|[\W_]+$', '', '_??cats--_')
你还可以查看这个 Python 示例:
import re
print( re.sub(r'^\W+|\W+$', '', '??cats--') ) # => cats
print( re.sub(r'^[\W_]+|[\W_]+$', '', '_??cats--_') ) # => cats
11
def strip_nonalnum(word):
if not word:
return word # nothing to strip
for start, c in enumerate(word):
if c.isalnum():
break
for end, c in enumerate(word[::-1]):
if c.isalnum():
break
return word[start:len(word) - end]
print([strip_nonalnum(s) for s in thelist])
或者
import re
def strip_nonalnum_re(word):
return re.sub(r"^\W+|\W+$", "", word)