大家都在想,我是如何制作一个程序来检查一个字符串,使它只包含2个或3个数字和4个字母。
示例
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") 越简单越好,因为我对编程很陌生。
发布于 2022-02-19 17:12:48
我只需循环遍历所有字母、有多少个和所有数字相同的数字,然后检查它是否符合您的条件,如下所示:
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")https://stackoverflow.com/questions/71187224
复制相似问题