HomePython Page 7 - Python 101 (part 5): Snake Oil For The Soul
String Theory - Python
Now that you know how to create and use Python's tuples, listsand dictionaries, it's time to get your hands dirty. In this article, findout how to read from, and write to, files on the filesystem with built-inPython methods, and also take a look at some of the new features availablein Python 2.x.
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.