Reputation: 9
I'm currently learning beginning course in Python and trying to solve this below question. I need see if characters in valid_characters are matching with the given samples and have either True or False but having big trouble. Could you please help me find out how to solve this?
- There are a lot of use cases where we want to check to see if a string has any invalid characters in it. For example, when asking for a credit card number, we want to make sure there are no non-numerals (although we might accept dashes or spaces). When asking for a name, we want to make sure all the characters are letters, spaces, or the occasional punctuation mark.
Write a function called is_valid. is_valid should take two parameters: a string to check, and a string of all valid characters.
is_valid should return the boolean True if all the characters in the string to check are present in the string of valid characters. It should return False if any character in the checked string does not appear.
Add your code here!
def is_valid(a_string, valid_characters):
for letter in valid_characters:
if letter in a_string:
return True
else:
return False
Below are some lines of code that will test your function. You can change the value of the variable(s) to test your function with different inputs.
If your function works correctly, this will originally print True, then False
sample_valid_string = "1234-5678-9011-1111"
sample_invalid_string = "1234!5678.9011?1111"
valid_characters = "0123456789-"
print(is_valid(sample_valid_string, valid_characters))
print(is_valid(sample_invalid_string, valid_characters))
Upvotes: 0
Views: 289
Reputation: 27033
The logic in the original question is not quite right. It will also only ever consider the first character before returning.
This might be better:
def is_valid(a_string, valid_characters):
for c in a_string:
if c not in valid_characters:
return False
return True
Upvotes: 2
Reputation: 51653
You are checking if all your valid characters are in your string.
This would work for
word = "abcdefg"
allowed = "ab" # a is in word and b is in word as well
is_valid(word, allowed)
but does not check if all your words letters are in the allowed letters....
Turn the check around and check if all letters of your word are in allowed letters.
Upvotes: 1