Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if the python string contains specific characters

Tags:

python-3.x

I have to write a program that prompts user for input and should print True only if every character in string entered by the user is either a digit ('0' - '9') or one of the first six letters in the alphabet ('A' - 'F'). Otherwise the program should print False.

I can't use regex for this question as it is not taught yet, i wanted to use basic boolean operations . This is the code I have so far, but it also outputs ABCH as true because of Or's. I am stuck

string = input("Please enter your string: ")

output = string.isdigit() or ('A' in string or 'B' or string or 'C' in string or 'D' in string or 'E' in string or 'F' in string)

print(output)

Also i am not sure if my program should treat lowercase letters and uppercase letters as different, also does string here means one word or a sentence?

like image 328
Aayush Gupta Avatar asked Jul 08 '26 17:07

Aayush Gupta


1 Answers

We can use the str.lower method to make each element lowercase since it sounds like case is not important for your problem.

string = input("Please enter your string: ")
output = True # default value

for char in string: # Char will be an individual character in string
    if (not char.lower() in "abcdef") and (not char.isdigit()):
        # if the lowercase char is not in "abcdef" or is not a digit:
        output = False
        break; # Exits the for loop

print(output)

output will only be changed to False if the string fails any of your tests. Otherwise, it will be True.

like image 117
SyntaxVoid supports Monica Avatar answered Jul 11 '26 22:07

SyntaxVoid supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!