Skip to content
Home » String Boolean Methods in Python

String Boolean Methods in Python

Spread the love

Today we’ll be talking about string boolean methods.

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:

1) formatting methods

2) statistical methods

3) searching methods

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

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

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

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version of the article:


Spread the love

Leave a Reply