简体   繁体   English

检查字符串是否包含 integer python

[英]check if string contains an integer python

I need to check if a character entered in a password contains an integer or not.我需要检查密码中输入的字符是否包含 integer。

password = input("Enter a password:" )
for num in password:
    if num.isdigit():
        break
    else:
        print("Your password must contain a number.")

The code above doesn't work because I'm assuming due to python 3 taking every user input as a string, it checks the string and never knows the difference between the string and the integer in the string.上面的代码不起作用,因为我假设由于 python 3 将每个用户输入作为字符串,它检查字符串并且永远不知道字符串和字符串中的 integer 之间的区别。 How would I get around this?我将如何解决这个问题?

Your code works fine if you unindent the else to make it part of the for :如果您取消缩进else使其成为for一部分,则您的代码可以正常工作:

for num in password:
    if num.isdigit():
        break
else:
    print("Your password must contain a number.")

If it's part of the if , the else happens for every character that's not a digit;如果它是if的一部分,那么每个不是数字的字符都会发生else if it's part of the for , it happens at the end of the loop if the loop was never broken , which is the behavior you want.如果它是for的一部分,如果循环从未被破坏,它会在循环结束时发生,这是您想要的行为。

An easier way of writing the same check is with the any function ("if there aren't any digits..."):编写相同检查的更简单方法是使用any function (“如果没有任何数字......”):

if not any(num.isdigit() for num in password):
    print("Your password must contain a number.")

or equivalently with all ("if all the characters aren't digits..."):或等价于all (“如果所有字符都不是数字......”):

if all(not num.isdigit() for num in password):
    print("Your password must contain a number.")

Your code will print Your password must contain a number.您的代码将打印Your password must contain a number. for every non-digit character.对于每个非数字字符。 You need to know if there is a digit in the password or not, then make decision about its validity.您需要知道密码中是否有数字,然后决定其有效性。 So you can use a boolean variable, then if any digit character found in the password, the variable would be True and after for loop you will use it for checking the validity of password.因此,您可以使用 boolean 变量,然后如果在密码中找到任何数字字符,则该变量将为True并且在for循环之后您将使用它来检查密码的有效性。

You can do like this:你可以这样做:

password = input("Enter a password:" )
good_pass = False

for num in password:
    if num.isdigit():
        good_pass = True
        break

if good_pass == True:
    print('Good password!')
else:
    print("Your password must contain a number.")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM