Python: Check if a character or substring is in a string
How to check if a character / substring is in a string or not#
Let me start with a little history about myself. I have been developing on the Web for more than five years now - in PHP. Yes, in goddamn PHP! I had been exposed to Python much earlier, but for some strange reason I never made the effort to learn it or use it. If I had learnt Python earlier, I wouldn't be struggling to to check if a substring exists in a string or not, today.
On the brighter side, I realize what a beautifully designed language Python is; and I make notes in the form of posts like this which other Python beginners might find handy. I am gonna be making a huge lot of useful posts related to Python among other stuff on my website, which is good.
Coming back to the topic "how do you check if a substring or character is there in a string". A character is also a substring technically, anyway, this is how you do it.
if 'c' in 'Python':
print 'YES'
else:
print 'NO'
Isn't that so beautifully simple?
When faced with the problem, my brain being damaged temporarily by PHP, I started to think in terms of PHP's own substr()
and strpos()
functions, and started looking for similar functions in Python. I did get them, str.find()
and str.index()
, but turns out they are best used when you want to know the position of the substring. For checking if a substring or character exists in a string, you use the in
operator instead.
Excuse me, but Python is a fuckin beautiful language!
Exercise#
- What is the opposite of the
<strong>in</strong>
operator? - What is the difference between
str.find()
andstr.index()
?