How to Compare Strings in Python?

Estimated read time 2 min read

To compare strings in Python, you can use various comparison operators and methods. Here are several ways to compare strings:

  1. Using comparison operators:
    • == to check if two strings are equal.
    • != to check if two strings are not equal.
    • < to check if one string is lexicographically smaller (comes before) another string.
    • > to check if one string is lexicographically greater (comes after) another string.
    • <= to check if one string is lexicographically smaller or equal to another string.
    • >= to check if one string is lexicographically greater or equal to another string.

Example:

string1 = "apple"
string2 = "banana"

if string1 == string2:
    print("The strings are equal.")
elif string1 < string2:
    print("string1 comes before string2.")
else:
    print("string1 comes after string2.")
  1. Using string methods:
    • str.startswith(prefix) to check if a string starts with a specific prefix.
    • str.endswith(suffix) to check if a string ends with a specific suffix.
    • str.find(substring) to check if a substring is present within a string.
    • str.count(substring) to count the occurrences of a substring within a string.

Example:

string = "Hello, world!"

if string.startswith("Hello"):
    print("The string starts with 'Hello'.")

if string.endswith("world!"):
    print("The string ends with 'world!'.")

if string.find("world") != -1:
    print("The string contains 'world'.")

print("The string has", string.count("o"), "occurrences of 'o'.")
  1. Using case-insensitive comparisons:
    • str.lower() or str.upper() to convert strings to lowercase or uppercase, respectively, for case-insensitive comparisons.
    • str.lower() == other_string.lower() to compare two strings in a case-insensitive manner.

Example:

string1 = "Apple"
string2 = "apple"

if string1.lower() == string2.lower():
    print("The strings are equal (case-insensitive).")

These are some of the ways you can compare strings in Python. Choose the method that best suits your specific comparison needs based on the desired behavior and the comparison criteria.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply