Reputation: 135
How to check if a string has at least one of certain character?
If the string cool = "Sam!"
, how do i check to see if that string has at least one !
Upvotes: 3
Views: 179
Reputation: 5258
In Python, a string is a sequence (like an array); therefore, the in
operator can be used to check for the existence of a character in a Python string. The in
operator is used to assert membership in a sequence such as strings, lists, and tuples.
cool = "Sam!"
'!' in cool # True
Alternately you can use any of the following for more information:
cool.find("!") # Returns index of "!" which is 3
cool.index("!") # Same as find() but throws exception if not found
cool.count("!") # Returns number of instances of "!" in cool which is 1
More info that you may find helpful:
http://www.tutorialspoint.com/python/python_strings.htm
Upvotes: 2
Reputation: 44838
Use the following
cool="Sam!"
if "!" in cool:
pass # your code
Or just:
It_Is="!" in cool
# some code
if It_Is:
DoSmth()
else:
DoNotDoSmth()
Upvotes: 1
Reputation: 52081
Use the in
operator
>>> cool = "Sam!"
>>> '!' in cool
True
>>> '?' in cool
False
As you can see '!' in cool
returns a boolean and can be used further in your code
Upvotes: 4