Python Part 3 – Changing text case and using the replace function

In this part of the tutorial we will look at how to change the case of a string to lower or upper case; as well as using the replace function to replace specific letters or text within a string.

Changing text to lower case in Python

my_name = “ADAM”
print(my_name.lower())

From the code above we are assigning a variable called my_name the value of ADAM. Once assigned we are passing this into the Print function and using the lower() function to change the string to lowercase.

This then prints the result of adam.

Changing text to upper case in Python

my_name = “adam”
print(my_name.upper())

Similarly if we are looking to change text to upper case we simply use the upper() function after the variable that we wish to affect.

Using the replace function in Python

Another handy function that exists inside Python is the replace function. This allows the user to pass two variables inside the function that tells the interpreter what letters or whole words to replace within the provided strings as shown in the below examples.

random_string = “Hi, viewer!”
print(random_string.replace(“i”,”o”))

random_string = “Hi, viewer!”
print(random_string.replace(“Hi”,”Hey”))

random_string = “Hi 5 Bob!”
print(random_string.lower().replace(“hi”,”hey”))

You can also use multiple python functions in conjunction with one another as also shown in the above example.

Leave a Comment