我正在尝试验证最后一个字符是否不在我的列表中
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:字符串索引超出范围
答案 0 :(得分:2)
您可以从负数(字符串或列表的末尾)开始索引
def acabar_char(input, list_cars):
return input[-1] is not in list_chars
答案 1 :(得分:0)
您已经在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
答案 2 :(得分:0)
似乎您试图断言输入字符串(或列表/元组)的最后一个元素不在不允许的字符子集中。
当前,由于您在循环内使用return
,因此循环甚至无法进行第二次或更多次迭代。因此,只有输入长度为1时,才会检查输入的最后一个元素。
我建议改为这样(也使用string.ascii_letters
定义):
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
这对您有用吗?
答案 3 :(得分:-1)
document.aggs.bucket('per_tag', 'terms', field='community__id')