如何删除字符串开头或结尾的非字母数字字符
问题描述:
我有一个列表,其中的元素在每个字符串的开头或结尾都有不必要的(非字母数字)字符.
I have a list with elements that have unnecessary (non-alphanumeric) characters at the beginning or end of each string.
例如.
'cats--'
我想摆脱-
我尝试过:
for i in thelist:
newlist.append(i.strip('\W'))
那没有用.有任何建议.
That didn't work. Any suggestions.
答
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)