Skip to main content
 首页 » 编程设计

python之当省略字符串中的任何非数字字符时,为什么这些字母会保留

2025年05月04日20TianFang

<分区>

因此,我测试了在 Python 中从不是数字的字符串中省略任何字符的不同方法。

在使用下面这种特殊的方法时,我发现在这种方法之后仍然保留了一些拉丁字母表中的字符:

代码

def get_lengths(): 
    books = [] 
    while True: 
        book = input() 
        for a in book: 
            books.append(a) 
        if book in ['stop', 'Stop']: 
            break 
    numbers = '0123456789' 
    characters = list(books) 
    print(characters) 
    for b in characters: 
        if b not in list(numbers): 
            del characters[characters.index(b)] 
    print(characters) 

输入

144 Leaves of Grass 
766 game of Thrones 
stop 

输出

['1', '4', '4', ' ', 'L', 'e', 'a', 'v',  
'e', 's', ' ', 'o', 'f', ' ', 'G', 'r',  
'a', 's', 's', '7', '6', '6', ' ', 'g',  
'a', 'm', 'e', ' ', 'o', 'f', ' ', 'T',  
'h', 'r', 'o', 'n', 'e', 's', 's', 't',  
'o', 'p'] 
 
['1', '4', '4', 'L', 'f', 'G', 'a', '7',  
'6', '6', 'g', 'a', 'm', ' ', 'f', ' ',  
'T', 'r', 'n', 'e', 's', 's', 't', 'p'] 

输出的前半部分是省略前的字符串。后半部分处理省略后的字符串,这里只保留数字。

所以我的问题是,为什么当所有非数字字符都被编程为从字符串中删除时,拉丁字母表中的各种字符仍然存在?

附言我知道这种省略所有非数字字符的方法有点不切实际,但请记住,我正在测试几种不同的方法。

另外,不用担心变量名,当我开始测试这些方法时,我正在做一个不同的项目。