检查列表的最后一个元素是否为数字

问题描述 投票:0回答:1

我有一个函数,该函数生成带有空格的随机字符[a-Z0-9],并将每个字符附加到list

words = []

while words.count(' ') < 10:
    if len(words) == 0:
        # append character
    else:
        if words[-1].isdigit(): # checking if last character is digit
            # append only digit or whitespacce
        else:
            # append character

您可以看到最后一个(上一个)字符是否为数字,我尝试仅附加数字或空格,否则附加任何字符。问题是,当我运行代码时,出现以下错误:

'NoneType' object has no attribute 'isdigit'对于行if words[-1].isdigit():。我做错了什么,为什么用None而不是str

python
1个回答
0
投票
if words[-1] in '0123456789': ...
© www.soinside.com 2019 - 2024. All rights reserved.