Replacing a substring of a string with Python

kwikness picture kwikness · May 3, 2012 · Viewed 23.9k times · Source

I'd like to get a few opinions on the best way to replace a substring of a string with some other text. Here's an example:

I have a string, a, which could be something like "Hello my name is $name". I also have another string, b, which I want to insert into string a in the place of its substring '$name'.

I assume it would be easiest if the replaceable variable is indicated some way. I used a dollar sign, but it could be a string between curly braces or whatever you feel would work best.

Solution: Here's how I decided to do it:

from string import Template


message = 'You replied to $percentageReplied of your message. ' + 
    'You earned $moneyMade.'

template = Template(message)

print template.safe_substitute(
    percentageReplied = '15%',
    moneyMade = '$20')

Answer

Raymond Hettinger picture Raymond Hettinger · May 3, 2012

Here are the most common ways to do it:

>>> import string
>>> t = string.Template("Hello my name is $name")
>>> print t.substitute(name='Guido')
Hello my name is Guido

>>> t = "Hello my name is %(name)s"
>>> print t % dict(name='Tim')
Hello my name is Tim

>>> t = "Hello my name is {name}"
>>> print t.format(name='Barry')
Hello my name is Barry

The approach using string.Template is easy to learn and should be familiar to bash users. It is suitable for exposing to end-users. This style became available in Python 2.4.

The percent-style will be familiar to many people coming from other programming languages. Some people find this style to be error-prone because of the trailing "s" in %(name)s, because the %-operator has the same precedence as multiplication, and because the behavior of the applied arguments depends on their data type (tuples and dicts get special handling). This style has been supported in Python since the beginning.

The curly-bracket style is only supported in Python 2.6 or later. It is the most flexible style (providing a rich set of control characters and allowing objects to implement custom formatters).