Why is the output of both print commands different. | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
0

Why is the output of both print commands different.

course="Python For Beginners" print(course.find("B")) print(course.find("b"))

23rd Nov 2020, 4:30 PM
Jurence
Jurence - avatar
3 Respostas
+ 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)])
23rd Nov 2020, 6:25 PM
Lothar
Lothar - avatar
+ 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.
23rd Nov 2020, 4:32 PM
šŸ‡ Alex Tușinean šŸ’œ
šŸ‡ Alex Tușinean šŸ’œ - avatar
+ 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".
23rd Nov 2020, 4:39 PM
Ipang