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.
- str(obj)
- repr(obj)
- `obj`
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:
Post a Comment