我创建了一个函数来比较my_word和other_word中的字符。 my_word是带有'_'字符的字符串,other_word是具有常规英语单词的字符串。
该函数返回:boolean,如果my_word的所有实际字母都与
other_word的对应字母,或者字母为特殊符号
'_'和my_word和other_word的长度相同;否则为False。
提示:字母(_)不能为1
other_word中已经显示的字母中的一个。因此,如果运行match_with_gaps(“a_ ple”,“apple”),则返回False。
这是代码:

`def match_with_gaps(my_word, other_word):
    my_word=my_word.replace(' ','')
    if len(my_word)==len(other_word):
        for char1 in my_word:
            if char1 not in other_word and char1 != '_':
                return False
        my_list=list(my_word)
        other_list=list(other_word)
        for w in my_list:
            if other_list.count(w)>1:
              return False
        return True
    else: return False`
运行代码。它返回SyntaxError:标识符中的无效字符
行:if other_list.count(w)> 1。但是我认为使用list.count()函数是可以接受的。
它出什么问题了?

最佳答案

我复制了您的代码并进行了清理。 1之后的冒号未被识别为冒号。您在代码的开头和结尾处也有一个'字符。现在可以正常工作:

def match_with_gaps(my_word, other_word):
    my_word=my_word.replace(' ','')
    if len(my_word)==len(other_word):
        for char1 in my_word:
            if char1 not in other_word and char1 != '_':
                return False
        my_list=list(my_word)
        other_list=list(other_word)
        for w in my_list:
            if other_list.count(w)>1:
                return False
        return True
    else:
        return False

关于python - SyntaxError :invalid character in identifier. But I don't why it goes wrong,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/65820772/

10-12 17:00