python - 每个测试值只给出一个输出
问题描述
这是一个用于挑选带有数字的字符串的程序。如果每个输入中有超过 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
解决方案
要检查字符/字符串是否为数字,只需使用 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))
推荐阅读
- ruby-on-rails - rails 中的混合复合键 - 使用 jsonb 字段和 db 列
- neo4j - 自动递增 id Neo4j 以按插入顺序检索元素
- python - 使用 Python (Flask/Postgresql) 的 DataTables 服务器端处理
- java - 如何使用 Camera2 API 获得稳定的恒定帧速率?
- c - 我可以重用请求对象吗?
- r - 抓取问答可以正常工作,除非一篇帖子的答案超过一页
- python - 根据分数对 CSV 文件进行排序
- scheme - 每次迭代如何保存新文件
- firebase - 将数据从 Firestore 加载到 BigQuery 的适当方法是什么?
- javascript - 使用 HTML 表单在 jQuery 中重定向