如何删除字符串开头或结尾的非字母数字字符 [英] How to rermove non-alphanumeric characters at the beginning or end of a string

查看:298
本文介绍了如何删除字符串开头或结尾的非字母数字字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,其中的元素在每个字符串的开头或结尾都有不必要的(非字母数字)字符.

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)

这篇关于如何删除字符串开头或结尾的非字母数字字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆