Thursday, 16 July 2009

String formatting with Python

Replacing a string:
$ python
>>> name = u'Lāsma'
>>> letter = 'Dear customer,\n Our customer service is the best.'
>>> letter = letter.replace('customer', name, 1) #replace only the first 'customer'
>>> print letter
Dear Lasma,
Our customer service is the best.
>>>


Dictionary based string formatting:
$ python
>>>name = u'Lāsma'
>>>sentence = 'My name is %(name)s"
>>>print sentence % vars()
My name is Lāsma
>>>

No comments: