Monday, August 10, 2009

Python Strings

Just watched the basic and advanced tutorials on Python Strings over at adaptivelearningonline.net . Here are my notes on Python Strings.

When we concatenate a String with another object, we will get an Exception if the other object is not a String. In such cases we should convert the other object to a String. There are a few methods which will convert non string objects to Strings. Assuming obj is a non string.

  1. str(obj)
  2. repr(obj)
  3. `obj`
Strings have a find method which will find a substring within a String and return the index where the substring starts.

We can change the case of a String using the upper() and lower() methods. Note that these methods return the changed String and do not change the existing String (since String objects are immutable)

>>> s = "HeLlo"
>>> upper(s)
>>> s.upper()
'HELLO'
>>> s.lower()
'hello'
>>> s
'HeLlo'

Strings also have a join method which can be used to join a list with a String, such that the String delimits every element from the list.

>>> words = ['hello', 'howdy', 'namaste']
>>> s = ':'
>>> s.join(words)
'hello:howdy:namaste'

We can replace characters or parts of a String using the replace() method.

>>> hello = 'hello'
>>> hello.replace('e', 'g')
'hgllo'
>>> hello.replace('hell', 'heaven')
'heaveno'

No comments: