首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何检查字符串,使其只包含一定数量的数字和字符

如何检查字符串,使其只包含一定数量的数字和字符
EN

Stack Overflow用户
提问于 2022-02-19 17:07:35
回答 1查看 37关注 0票数 -1

大家都在想,我是如何制作一个程序来检查一个字符串,使它只包含2个或3个数字和4个字母。

示例

代码语言:javascript
复制
string = input("Please enter a string: ") #example string would be HY21 4KK  
if  
string contains 2-3 characters
string contains 4 letters  
print("This is valid")  
else   
Print("This is invalid")  

越简单越好,因为我对编程很陌生。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-02-19 17:12:48

我只需循环遍历所有字母、有多少个和所有数字相同的数字,然后检查它是否符合您的条件,如下所示:

代码语言:javascript
复制
import string

# string.ascii_lowercase is "abdcdef..."
# string.ascii_uppercase is "ABCDEF..."
# so string.ascii_lowercase + string.ascii_uppercase will be all lowercase letter, and then all uppercase letters.
# string.digits is "01234567890"

e = input("Please enter a string: ")
# Here we will sum the number of appearances of every letter, lower case or upper case, in the English alphabet
# to get the total number of letters in e:
letter_count = sum(e.count(i) for i in string.ascii_lowercase + string.ascii_uppercase)
# Same here except with all digits:
digit_count = sum(e.count(i) for i in string.digits)

if digit_count in [2, 3] and letter_count == 4:
    print("This is valid")
else:
    print("This is invalid")
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71187224

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档