Why didn’t it work when I used a string method and then printed my string?


#1

Question

Why didn’t it work when I used a string method and then printed my string?

Answer

Recall that variables are kind of like boxes that store values. We can think of these string methods as standalone operations that just happen and then the program moves on.
If you create a variable and on the next line use a string method, like my_string.upper(), it does not change the string stored in your my_string variable. It only performs that operation and then moves on.
If you want to actually change your stored string to uppercase, you would have to assign your string the value of itself to uppercase! Take a look at the code below for a better understanding:

my_string = “i’m a string that started as lowercase”
my_string.upper()   # This DOES NOT change the value stored in my_string
print my_string   # This will print the lowercase version since it didn’t change

# Displaying uppercase but not actually changing the value of my_string:
print my_string.upper()   # Prints uppercase but doesn’t change my_string’s value
print my_string   # Prints lowercase version since value didn’t change

# Actually changing the value of the variable:
my_string = my_string.upper()
print my_string   # Prints all uppercase version since the value was updated


FAQ: Learn Python – Strings & Console Output – And Now, For Something Completely Familiar
#3

That answer was great! Thanks