Reputation: 11
I'm trying to find out if there's a simple means using for loops and lists to check if a user input string contains letters or letters and an apostrophe, but not numbers or letters and numbers (letters and numbers and an apostrophe)?
I have tried numerous methods and cannot seem to figure it out? I'd appreciate any leads! Thanks.
Upvotes: 1
Views: 2060
Reputation: 180391
You can also use set.issuperset
specifying a set of allowed characters:
from string import ascii_letters
allowed = set(ascii_letters+"'")
test = ['abcde', "abcde'", 'abcde123', "abcde'123", 'abcde.']
for s in test:
print("{} {}".format(s, allowed.issuperset(s)))
Output:
abcde True
abcde' True
abcde123 False
abcde'123 False
abcde. False
Upvotes: 1
Reputation: 18457
You seem to want only strings that contain letters (plus maybe an apostrophe), but no numbers, though you have expressed the requirements more verbosely. This can be accomplished without regexes as follows:
not any(c for c in my_str if c not in string.ascii_letters + "'")
See the following example code:
>>> test = ['abcde', "abcde'", 'abcde123', "abcde'123", 'abcde.']
>>> for s in test:
... print(s, '-->', not any(c for c in s if c not in string.ascii_letters + "'"))
...
abcde --> True
abcde' --> True
abcde123 --> False
abcde'123 --> False
abcde. --> False
Hopefully it's obvious that it would be more efficient to do the string.ascii_letters + "'"
only once, and that you must import string
first. This is just an example.
Upvotes: 2