In our last article we left off discussing ways to manipulate strings in Python, like concatenating, repeating, escape characters, and so forth. In this episode we will pick up where we left off and learn some more ways to work with strings, starting with the comparison method.
We can also use methods to control the appearance of strings, as in the following examples. In our first code, we will make the first letter of our string uppercase, using the capitalize method():
'It was a dark and stormy night, the wind blowing through the trees, and somewhere, out there in the far off teinkling of city lights, britney spears was busy being a bad mother...'
You will note that nothing really changed since our text was already capitalized to begin with.
In this next example we will use the title method() to capitalize the first letter of every word:
'It Was A Dark And Stormy Night, The Wind Blowing Through The Trees, And Somewhere, Out There In The Far Off Teinkling Of City Lights, Britney Spears Was Busy Being A Bad Mother...'
And to make every letter uppercase, we use the upper method():
'IT WAS A DARK AND STORMY NIGHT, THE WIND BLOWING THROUGH THE TREES, AND SOMEWHERE, OUT THERE IN THE FAR OFF TEINKLING OF CITY LIGHTS, BRITNEY SPEARS WAS BUSY BEING A BAD MOTHER...'
I know, I know...hold back all your Britney is a Good Person YouTube videos. We're almost done.
And of course we can also change everything to lowercase, using the lower() method:
'it was a dark and stormy night, the wind blowing through the trees, and somewhere, out there in the far off teinkling of city lights, britney spears was busy being a bad mother...'
Also, you can switch between upper and lower using the swapcase() method. In or previous example, everything was changed to lower case. We can now use swapcase to switch back to uppercase. If we wanted to switch back to lowercase after that, we could again use switchase:
'iT WAS A DARK AND STORMY NIGHT, THE WIND BLOWING THROUGH THE TREES, AND SOMEWHERE, OUT THERE IN THE FAR OFF TEINKLING OF CITY LIGHTS, bRITNEY sPEARS WAS BUSY BEING A BAD MOTHER...'
As I said before, these are only a few of the string methods available; we will discuss the rest at a later date.