lettura simple

The lower() Method in Python

Python has a built-in function called the lower() method that has the ability to morph any given string into lowercase.

It becomes invaluable when you need to compare a string with another that might be in lowercase. For example, if you have a string like "HELLO WORLD", by using the lower() method, you can turn it into "hello world".

To put the lower() method into action, you just jot down the string object you're focusing on, add a dot, and then write the word 'lower' followed by parentheses - like this:

string.lower()

Let's walk through a real-world example.

Let's say we have a variable named "text" and we assign a string to it.

>>> text = "This is an EXAMPLE"

Next up, we apply the lower() method to our variable "text".

>>> text.lower()

What happens next is that every single letter in your string gets transformed into lowercase.

this is an example

A crucial point to remember here is that the lower() method doesn't meddle with your original string, but instead it generates a brand new one.

In our case here, the newly formed string gets assigned to the variable "text2".

>>> text2 = text.lower()

So, if you're looking to keep the result, you should assign it to a fresh variable or overwrite the existing one.

Did you know you can mix and match the lower() method with other string methods?

For example, you could pair the lower() method with the replace() method.

>>> text="my name is TOM"
>>> text2=text.lower().replace("tom", "Sam")
>>> print(text2)

In this script, the string "text" first undergoes transformation into lowercase via the lower() method.

Afterwards, it replaces the word "tom" with "Sam", storing the final output in the "text2" variable.

Finally, it prints the newly crafted string onto the screen.

my name is Sam




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin