首页 > 解决方案 > 每个测试值只给出一个输出

问题描述

这是一个用于挑选带有数字的字符串的程序。如果每个输入中有超过 1 个数字,它会重复输出。

例如,我有“test123”作为输入,程序会给我其中的 3 个作为输出,因为其中有 3 个数字。

我只是一个python自学初学者,所以请帮助我,感谢您的时间,祝您有美好的一天!

num_list = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
f = open("testfile.tsv", "r")
content = f.read()
content_list = content.splitlines()
f.close()

def split(stuff): 
    return [char for char in stuff]

for a in content_list:
    words = split(a)
    for b in words:
        if b in num_list:
            print(a)
            

仅供参考:“testfile.tsv”:

test
test123
testing
123
123456

标签: pythonsorting

解决方案


要检查字符/字符串是否为数字,只需使用 isnumeric()。

IE

def split(stuff): 
    return [char for char in stuff]


f = open("testfile.tsv", "r")
content = f.read()
content_list = content.splitlines()
f.close()

for a in content_list:
    words = split(a)
    num_count = 0
    for b in words:
        if b.isnumeric():
            num_count += 1
    print("%s has %d numbers" % (a, num_count))


推荐阅读