Today we’ll be talking about string boolean methods.
In my previous articles I covered quite a few string methods. If you haven’t read those articles, feel free to do it. Here they are:
The startswith and endswith Methods
There are a couple of methods that return True or False. One of them is startswith(prefix[, start, past]), which checks if the string or substring (if the optional start and past parameters are given) start with prefix:
>>> text = "So, come and help me."
>>> text.startswith("So")
True
Let’s check the substring from index 4 to the end:
>>> text.startswith("c", 4)
True
Now let’s check the slice between index 3 and 7:
>>> text.startswith("So", 3, 8)
False
There’s also the method endswith(suffix[, start, past]), which checks if the string or substring (if the optional start and past parameters are given) ends with suffix:
>>> text = "Are you OK?"
So, does the string end with a question mark? Yes, it does.
>>> print(text.endswith("?"))
True
Does the slice between index 1 and 6 (so “re you”) end in “ou”. Yep.
>>> print(text.endswith("ou", 1, 7))
True
The islower, isupper and istitle Boolean Methods
The method islower returns True if the all the letters in the string are lowercase:
>>> "we are all lowercase letters! more than 10 of us.".islower()
True
The isupper method returns True if all the letters in the string are uppercase:
>>> "10 GREEN BOTTLES COMIN' TO TOWN".isupper()
True
The method istitle returns True if all the letters in the string are titlecase characters, i.e. each word starts with a capital letter. Other characters are ignored, but there must be at least one letter.
>>> "The War Of The Giants".istitle()
True
>>> "The War of the Giants".istitle()
False
>>> "5 Orange Bathtubs".istitle()
True
>>> "$5 Journey - The Beginning".istitle()
True
>>> "14".istitle()
False
>>> "A14".istitle()
True
Here’s the video version of the article: