Converting a Python String to Lowercase String

Lowercase String

A lowercase string is a string where all the letters are in lowercase. In other words, all the alphabets in the string are in their small form. For example, “hello world” is a lowercase string, while “Hello World” or “HELLO WORLD” are not lowercase strings. In python, the ‘str.lower()' method is used to convert a string to lowercase.

Lowercase a String in Python

You can use the ‘str.lower()‘ method to lowercase a string in Python.

Example:

Python
string = "HELLO WORLD"
print(string.lower())

Output:

hello world

Compare Lowercase String in Python

To compare lowercase strings in Python, you can convert the strings to lowercase using the .lower() method, and then compare the lowercase versions of the strings. Here’s an example:

Python
str1 = "Hello"
str2 = "hello"

if str1.lower() == str2.lower():
    print("The strings are equal, ignoring case.")
else:
    print("The strings are not equal.")

In this example, ‘str1‘ and ‘str2‘ are two strings that are equal in meaning but have different cases. By converting both strings to lowercase using the ‘.lower()‘ method, we can compare them without considering case. The output of this code will be:

The strings are equal, ignoring case.

Note that this approach works only for ASCII strings. If you need to compare strings in a case-insensitive way for a language with non-ASCII characters, you may need to use a more sophisticated approach, such as using the ‘casefold()‘ method instead of ‘lower()‘.

Lowercase string use in Searching

To use lowercase string in searching, you can convert both the search term and the text being searched to lowercase using the ‘.lower()‘ method, and then perform the search. Here’s an example:

Python
search_term = "apple"
text = "I like to eat apples, especially green apples."

if search_term.lower() in text.lower():
    print("The search term was found in the text.")
else:
    print("The search term was not found in the text.")

In this example, ‘search_term‘ is the term we want to search for in ‘text‘. By converting both the search term and the text to lowercase using the ‘.lower()‘ method, we can perform a case-insensitive search. The output of this code will be:

The search term was found in the text.

Note that this approach works only for ASCII strings. If you need to search for strings in a case-insensitive way for a language with non-ASCII characters, you may need to use a more sophisticated approach, such as using the ‘casefold()‘ method instead of ‘lower()‘.

Share The Tutorial With Your Friends
Twiter
Facebook
LinkedIn
Email
WhatsApp
Skype
Reddit

Check Our Ebook for This Online Course

Advanced topics are covered in this ebook with many practical examples.