Learning objectives
By the end of this section you should be able to
- Compare strings using logical and membership operators.
- Use
lower()
andupper()
string methods to convert string values to lowercase and uppercase characters.
String comparison
String values can be compared using logical operators (<
, <=
, >
, >=
, ==
, !=
) and membership operators (in
and not in
). When comparing two string values, the matching characters in two string values are compared sequentially until a decision is reached. For comparing two characters, ASCII values are used to apply logical operators.
Operator | Description | Example | Output | Explanation |
---|---|---|---|---|
|
Checks whether the first string value is greater than (or greater than or equal to) the second string value. |
|
|
When comparing |
|
Checks whether the first string value is less than (or less than or equal to) the second string value. |
|
|
When comparing |
|
Checks whether two string values are equal. |
|
|
Since all characters in the first operand and the second operand are the same, the two string values are equal. |
|
Checks whether two string values are not equal. |
|
|
The two operands contain different string values ( |
|
Checks whether the second operand contains the first operand. |
|
|
Since string |
|
Checks whether the second operand does not contain the first operand. |
|
|
Since string |
Concepts in Practice
Using logical and membership operators to compare string values
lower() and upper()
Python has many useful methods for modifying strings, two of which are lower()
and upper()
methods. The lower() method returns the converted alphabetical characters to lowercase, and the upper() method returns the converted alphabetical characters to uppercase. Both the lower()
and upper()
methods do not modify the string.
Example 8.1
Converting characters in a string
In the example below, the lower()
and upper()
string methods are called on the string variable x
to convert all characters to lowercase and uppercase, respectively.
x = "Apples"
# The lower() method converts a string to all lowercase characters
print(x.lower())
# The upper() method converts a string to all uppercase characters
print(x.upper())
The above code's output is:
apples APPLES
Concepts in Practice
Using lower() and upper()
Try It
Number of characters in the string
A string variable, s_input
, is defined. Use lower()
and upper()
to convert the string to lowercase and uppercase, and print the results in the output. Also, print the number of characters in the string, including space characters.
Try It
What is my character?
Given the string, s_input
, which is a one-character string object, if the character is between "a"
and "t"
or "A"
and "T"
, print True
. Otherwise, print False
.
Hint: You can convert s_input
to lowercase and check if s_input
is between "a"
and "t"
.