Course 2.2Lesson 4 of 5
A string can answer questions. The word in tells whether a piece of text is inside another text. startswith() and endswith() test the two ends, and isdigit(), isalpha() and isupper() test what kind of characters it has. These give True or False. count() counts how many times a piece occurs, find() gives the position of the first match or -1, and index() does the same but stops with an error when the piece is missing.
Try the code and the simulations beside the lesson.
After this lesson you can
So far we have made new text. Now we ask questions about text. Each of these gives True or False.
These answers are bool values, the fourth type of value. In the course on if, you will use them to make decisions: "if the text is a number, then calculate". For now, print them and read them.
You can use a position that find() gives in a slice. text[text.find(" ") + 1:] is everything after the first space.
With no second number, find() starts at position 0, so it gives the first match of the whole text.
The first word of a sentence ends at the first space. The position of the first space is sentence.find(" "). So the first word is sentence[:sentence.find(" ")]. For "Python is easy", find(" ") is 6, and sentence[:6] is Python. You will use this idea in the project.
in without a string on the left. 5 in "2026" is an error. Write "5" in "2026"."Python" in "python is fun" is False. Use .lower() on both sides first.isdigit() to accept a minus sign or a decimal point. "-5".isdigit() and "3.5".isdigit() are False.find() gives -1 when the piece is missing. A position of -1 is not the last position here.index() for something that may be missing. It stops with an error. Use find().Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
in, startswith(), endswith(), isdigit(), isalpha() and isupper() answer with True or False.count() counts a piece. find() gives the position of the first match, or -1.index() is like find() but stops with an error if the piece is not there.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
"cat" in "concatenate" and "Dog" in "dog"?"banana".count("a") and "banana".find("n") give?s is a whole number?"hello".find("z") give?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.