0
Why is the output of both print commands different.
course="Python For Beginners" print(course.find("B")) print(course.find("b"))
4 Réponses
+ 3
Enon Deogracious Jurence , the reason of getting -1 is that this character / substring is not found in the course string. You will get -1 for each character / substring you are searching for when it can NOT be found.
The advantage of using find() instead of index() is, that find() returns -1 when not found, as index() creates an exception in the same case.
If you want to find upper case character / substring as well as lower case, you can use:
course="Python For Beginners"
print(course.lower().find("n"))
# the code above does only find the first match, but "n" appears multiple times
# if you want to get the position of all occurrences, it is better to use regex:
import re
print([sub.start() for sub in re.finditer("n", course)])
+ 1
Because B is different from b.
If you search "b", you'll only find b and if you search B, you'll find B.
+ 1
Please tag this thread with Python, the one language relevant to the snippet example and the thread's topic 👍
string `find` method is case sensitive, "B" is different to "b". <course> is a string which contains "B" in it, but <course> doesn't contain a "b".