Python 在字符串中查找特殊符号

Python 在字符串中查找特殊符号,python,python-3.x,Python,Python 3.x,如何匹配字符串开头、结尾和中间的特殊符号? 我知道,我应该用正则表达式。例如,我制作了一个函数: def check_word(word: str) -> bool: special_symbols = '()1234567890!?_@#$%^&*.,' e = re.match(special_symbols, word) # How to match symbols at end? m = re.match(specia

如何匹配字符串开头、结尾和中间的特殊符号? 我知道,我应该用正则表达式。例如,我制作了一个函数:

    def check_word(word: str) -> bool:
        special_symbols = '()1234567890!?_@#$%^&*.,'
        e = re.match(special_symbols, word) # How to match symbols at end?
        m = re.match(special_symbols, word) # How to match symbols at middle?
        s = re.match(special_symbols, word) # How to match symbols at start?
        if e is not None:
             return True
        if m is not None:
             return True
        if s is not None:
             return True
        if e is not None and s is not None:
             return False
        if s is not None and m is not None:
             return False

print(check_word("terdsa223124")) # --> True
print(check_word("ter223124dsa")) # --> True
print(check_word("223124terdsa")) # --> True
print(check_word("223124terdsa223124")) # --> False
print(check_word("223124ter223124dsa")) # --> False

如何填充
re.match
,以便正确打印?

基于布尔运算,无需正则表达式即可轻松实现:

import itertools

def check_word(word):
    spec_symbols = '()1234567890!?_@#$%^&*.,'

    match = [l in spec_symbols for l in word]
    group = [k for k,g in itertools.groupby(match)]

    return sum(group) == 1


print(check_word("terdsa223124")) # True
print(check_word("ter223124dsa")) # True
print(check_word("223124terdsa")) # True
print(check_word("223124terdsa223124")) # False
print(check_word("223124ter223124dsa")) # False
您可以尝试以下方法:

import re
a = ["terdsa223124", "ter223124dsa", "223124terdsa", "223124terdsa223124"]
final_output = {s:any([re.findall('^[\d\W]+[a-zA-Z]+$', s), re.findall('^[a-zA-Z]+[\d\W]+[a-zA-Z]+$', s), re.findall('^[a-zA-Z]+[\d\W]+$', s)]) for s in a}
输出:

{'223124terdsa223124': False, '223124terdsa': True, 'terdsa223124': True, 'ter223124dsa': True}

使用
re.search
代替。这里也没有理由有三个单独的案例。只要使用
re.search
一次就可以了。@cᴏʟᴅsᴘᴇᴇᴅ 我读到了关于
re.search
。如果我理解正确,它会返回第一个匹配的值。在我的例子中,
print(检查单词(“223124terdsa223124”)
不会给出
False
是字符串
terdsa223124
m==True?@maximitarenko False因为m是中间匹配你能解释一下
^[\d\W]+[a-zA-Z]+$
是什么意思吗?@AlTs
^[\d\W]+[a-zA-Z]$
搜索你的第一个条件,即字符串以任何数字或非字母数字字符开头
^[\d\W]+
在字符串开头搜索数字或非字母数字字符,[a-zA-Z]+$将确定字符串结尾的其余部分包含字母字符。