Aayush Gupta
Aayush Gupta

Reputation: 446

Check if the python string contains specific characters

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?

Upvotes: 3

Views: 2164

Answers (1)

SyntaxVoid
SyntaxVoid

Reputation: 2633

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.

Upvotes: 2

Related Questions