我正在尝试验证最后一个字符是否不在我的列表中
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
您已经在for循环中遍历了列表,因此不需要使用索引。您可以使用列表理解作为另一个答案,但我猜您正在尝试学习python,因此这里将是重写函数的方法。你知道吗
你可以用负数从(刺或列表的)末尾建立索引
似乎您试图断言输入字符串(或列表/元组)的最后一个元素不在不允许的字符的子集中。你知道吗
目前,您的循环甚至从未进入第二次或更多次迭代,因为您在循环中使用
return
;因此,只有当输入的长度为1时,才检查输入的最后一个元素。你知道吗我建议这样做(也使用^{} 定义):
这对你有用吗?你知道吗
相关问题 更多 >
编程相关推荐