尝试验证字符串的最后位置

2024-09-27 00:23:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试验证最后一个字符是否不在我的列表中

def acabar_char(input):
    list_chars = "a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 1 2 3 4 5 6 7 8 9 0".split()
    tam = 0
    tam = (len(input)-1)
    for char in input:
        if char[tam] in list_chars:
            return False
        else:
            return True

当我尝试此操作时,出现以下错误:

if char[tam] in list_chars:

IndexError: string index out of range


Tags: in列表forinputlenreturnifdef
3条回答

您已经在for循环中遍历了列表,因此不需要使用索引。您可以使用列表理解作为另一个答案,但我猜您正在尝试学习python,因此这里将是重写函数的方法。你知道吗

list_chars = "a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 1 2 3 4 5 6 7 8 9 0".split()
for char in input:
    if char in list_chars:
        return False
return True

你可以用负数从(刺或列表的)末尾建立索引

def acabar_char(input, list_cars):
    return input[-1] is not in list_chars

似乎您试图断言输入字符串(或列表/元组)的最后一个元素不在不允许的字符的子集中。你知道吗

目前,您的循环甚至从未进入第二次或更多次迭代,因为您在循环中使用return;因此,只有当输入的长度为1时,才检查输入的最后一个元素。你知道吗

我建议这样做(也使用^{}定义):

import string
DISALLOWED_CHARS = string.ascii_letters + string.digits

def acabar_char(val, disallowed_chars=DISALLOWED_CHARS):
    if len(val) == 0:
        return False

    return val[-1] not in disallowed_chars

这对你有用吗?你知道吗

相关问题 更多 >

    热门问题