8.1 String operations
Learning objectives
By the end of this section you should be able to
- Compare strings using logical and membership operators.
- Use
lowerandupperstring 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 |
|---|---|---|---|---|
> or >= | Checks whether the first string value is greater than (or greater than or equal to) the second string value. | "c" > "d" | False | When comparing "c" operand to "d" operand, the ASCII value for "c" is smaller than the ASCII value for "d". Therefore, "c" < "d". The expression "c" > "d" evaluates to False. |
< or <= | Checks whether the first string value is less than (or less than or equal to) the second string value. | "ab" < "ac" | True | When comparing "ab" operand to "ac" operand, the first characters are the same, but the second character of "ab" is less than the second character in "ac" and as such "ab" < "ac". |
== | Checks whether two string values are equal. | "aa" == "aa" | True | 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. | "a" != "b" | True | The two operands contain different string values ("a" vs. "b"), and the result of checking whether the two are not the same evaluates to True. |
in | Checks whether the second operand contains the first operand. | "a" in "bc" | False | Since string "bc" does not contain string "a", the output of "a" in "bc" evaluates to False. |
not in | Checks whether the second operand does not contain the first operand. | "a" not in "bc" | True | Since string "bc" does not contain string "a", the output of "a" not in "bc" evaluates to True. |
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.