Python 101 (part 5): Snake Oil For The Soul - String Theory
(Page 7 of 8 )
Now, in addition to the various methods already explained in this andprevious articles, Python 2.0 comes with a whole bunch of new methods forthe various data types you've studied. Over the next couple of pages, I'dlike to briefly illustrate these with some examples.
A number of string methods are available to convert and check stringformats - take a look:
>>> # string methods
>>> str = "jackfrost"
>>> # check for lowercase
>>> str.islower()
1
>>> # check for uppercase
>>> str.isupper()
0
>>> # capitalize first character
>>> str.capitalize()
'Jackfrost'
>>> # convert to uppercase
>>> str.upper()
'JACKFROST'
>>> # convert to lowercase
>>> str.lower()
'jackfrost'
>>> # let's try another string
>>> str = "Jack Frost"
>>> # check if this is a title
>>> str.istitle()
1
>>> # split string and return sections as list
>>> str.split(" ")
['Jack', 'Frost']
>>> str.swapcase()
'jACK fROST'
>>> str = "Mummy"
>>> # count number of occurrences within a string
>>> str.count("m")
2
>>>
Incidentally, the count() method also works with lists.
>>> list = ["red", "green", "blue", "red", "yellow", "blue", "black",
"white", "green"]
>>> list.count("green")
2
>>>
Next: Pop() Goes The Weasel >>
More Python Articles
More By Vikram Vaswani, (c) Melonfire