Search⌘ K
AI Features

String Operations

Explore Python string operations such as lexicographic comparison, concatenation with the plus operator, string replication using the asterisk, and substring searches with membership operators. Understand how to manipulate and evaluate strings effectively for programming tasks, including practical exercises like generating email addresses.

Comparison operators

Strings are compatible with the comparison operators. Each character has a Unicode value. This allows strings to be compared on the basis of their Unicode values. When comparing strings, Python uses lexicographic ordering—each character is compared one by one and the string that comes first in the dictionary is said to have the smaller value. If the strings have different lengths and characters match up to the end of the shorter string, the shorter string is considered lexicographically smaller. Let’s look at a few examples:

Python 3.10.4
print('a' < 'b') # 'a' has a smaller Unicode value
house = "Gryffindor"
house_copy = "Gryffindor"
house_copy_longer = "Gryffindor_"
new_house = "Slytherin"
print(house == house_copy)
print(house == new_house)
print(new_house <= house)
print(new_house >= house)
print(house_copy <= house_copy_longer)

Explanation

Here’s the code explanation:

  • Line 1: Compares the characters a and b using the < operator. Since a has a smaller Unicode value than b, the result is True.

  • Line 3: Assigns the string Gryffindor to ...