How to Compare Strings with Boolean and Len in Python?

Estimated read time 2 min read

To compare strings using boolean expressions and the len() function in Python, you can utilize various comparison operators to check for different conditions. Here are some examples:

  1. Checking if two strings are equal:
string1 = "Hello"
string2 = "World"

if string1 == string2:
    print("The strings are equal.")
    print("The strings are not equal.")

In this example, the == operator is used to compare the strings string1 and string2 for equality.

  1. Checking if a string is empty:
string = ""

if not string:
    print("The string is empty.")
    print("The string is not empty.")

Here, the not keyword is used to check if the string is empty. An empty string evaluates to False in a boolean context.

  1. Comparing the lengths of two strings:
string1 = "Hello"
string2 = "World"

if len(string1) < len(string2):
    print("string1 is shorter than string2.")
elif len(string1) > len(string2):
    print("string1 is longer than string2.")
    print("string1 and string2 have the same length.")

In this example, the len() function is used to retrieve the lengths of string1 and string2, and the comparison operators <, >, and == are used to compare their lengths.

You can combine these comparisons and adapt them to your specific requirements. By using boolean expressions and the len() function, you can perform various comparisons on strings in Python based on their equality, emptiness, or length.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply