String Manipulation - Splitting strings, making cases
(Page 2 of 4 )
Splitting a string is something I find myself doing often. The split method is used for this:
>>> test.split()
['This', 'is', 'just', 'a', 'short', 'string.']
We can choose the point that we split it at:
>>> test.split ( 'a' )
['This is just ', ' short string.']
Rejoining our split string can be done using the join method:
>>> ' some '.join ( test.split ( 'a' ) )
'This is just some short string.'
We can play around with the case of letters in our string, too. Let's make it all upper case:
>>> test.upper()
'THIS IS JUST A SHORT STRING.'
Now let's make it lowercase:
>>> test.lower()
'this is just a short string.'
Let's capitalize only the first letter of the lowercase string:
>>> test.lower().capitalize()
'This is just a short string.'
We can also use the title method. This capitalizes the first letter in each word:
>>> test.title()
'This Is Just A Short String.'
Trading case is possible:
>>> test.swapcase()
'tHIS IS JUST A SHORT STRING.'
We can run a number of tests on strings using a few methods. Let's check to see whether a given string is all upper case:
>>> 'UPPER'.isupper()
True
>>> 'UpPEr'.isupper()
False
Likewise, we can check to see whether a string contains only lower case characters:
>>> 'lower'.islower()
True
>>> 'Lower'.islower()
False
Checking whether a string looks like a title is simple, too:
>>> 'This Is A Title'.istitle()
True
>>> 'This is A title'.istitle()
False
Next: Numbers and spaces >>
More Python Articles
More By Peyton McCullough