Skip to content
Home » String Comparison and Membership in Python

String Comparison and Membership in Python

Spread the love

Today we’ll be talking about string comparison and membership.

Here’s the video version of this article if you prefer to watch it first:

String Comparison

We can use all the comparison operators to compare strings. Each character in Unicode is represented by a number and these numbers are compared. This is how string comparing works. It means, the order is not strictly alphabetical, because all capital letters come before small letters in Unicode.

We have the following comparison operators:

comparison operators

These two should be equal:

>>> "hello" == "hello"
True

These should be not equal:

>>> a = "hello"
>>> b = "hi"
>>> a != b
True

The first character to differ is the second one, ‘i’ comes after ‘e’:

>>> "hi" > "hello"
True

Capital ‘Y’ comes before small ‘y’:

>>> "Yes" < "yes"
True

We can confirm this by means of the ord function, which gives us the Unicode number of the character:

>>> ord("Y"), ord("y")
(89, 121)

These two are equal, so the first one must also be greater or equal to the other:

>>> "hello" >= "hello"
True

‘F’ is a capital letter, so it comes earlier than any small letter. As ‘F’ is less than ‘a’, it’s automatically also less than or equal to ‘a’:

>>> "F" <= "a"
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).

Membership

We can check if a particular element is contained or not in the string. We use the membership operators in and not in:

>>> text = "I need help."
>>> "n" in text
True

>>> "i" in text  # Capital I is contained but not the small one.
False

>>> "Z" not in text
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.


Spread the love

Leave a Reply