python - 试图创建一个函数来返回字母、大写、小写、数字等的总数,但似乎无法正常工作 - Python
问题描述
def countCharacter(str):
for i in str:
letters = 0
if i.isalpha():
letters += 1
for i in str:
upper = 0
lower = 0
digit = 0
others = 0
if i.isupper():
upper += 1
elif i.islower():
lower += 1
elif i.isnumeric():
digit += 1
else:
others += 1
list = [letters, upper, lower, digit, others]
return list
print(countCharacter("wh12p3cmaLKND;'$%^&*"))
处理这个应该打印相应字符的数字列表但似乎不起作用的函数,
刚学python,求帮助
解决方案
尝试改用以下代码:
def countCharacter(string):
letters = sum(i.isalpha() for i in string)
upper = sum(i.isupper() for i in string)
lower = sum(i.islower() for i in string)
digit = sum(i.isdigit() for i in string)
others = len(string) - sum([upper, lower, digit])
return [letters, upper, lower, digit, others]
print(countCharacter("wh12p3cmaLKND;'$%^&*"))
或者修改您的原始代码:
def countCharacter(string):
letters = 0
for i in string:
if i.isalpha():
letters += 1
upper = 0
lower = 0
digit = 0
others = 0
for i in string:
if i.isupper():
upper += 1
elif i.islower():
lower += 1
elif i.isnumeric():
digit += 1
else:
others += 1
return [letters, upper, lower, digit, others]
print(countCharacter("wh12p3cmaLKND;'$%^&*"))
您的代码不起作用的原因是因为您正在覆盖变量并将它们设置回0
每次迭代。
推荐阅读
- html - 在自定义复选框旁边垂直居中文本?
- computer-vision - 如何设计视觉识别标签?
- c - 标准库中的某些函数只是看起来是包装器或别名的原因是什么?
- javascript - 使用 Express res.download 从文件共享中获取文件
- node.js - MongoDB:findOne返回null但集合中存在子文档
- python - Tensorflow/Keras 似乎改变了我的批量大小
- python - 如何过滤两个模型之间的差异?使用 django
- cypress - Percy - Cypress - 错误:找不到浏览器修订版 756035。运行“npm install”或“yarn install”下载浏览器二进制文件
- apache-kafka - Kafka Connect - JDBC Avro 连接如何定义自定义模式注册表
- reactjs - 我们不能直接将组件注入 App.js 吗?