24

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')
1
  • 1
    I would like to ask to reconsider to use standard format method if the $ format for substitutes is not unchangeble to {} May 3, 2012 at 19:03

6 Answers 6

57

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).

1
11

There are a number of ways to do it, the more commonly used would be through the facilities already provided by strings. That means the use of the % operator, or better yet, the newer and recommended str.format().

Example:

a = "Hello my name is {name}"
result = a.format(name=b)

Or more simply

result = "Hello my name is {name}".format(name=b)

You can also use positional arguments:

result = "Hello my name is {}, says {}".format(name, speaker)

Or with explicit indexes:

result = "Hello my name is {0}, says {1}".format(name, speaker)

Which allows you to change the ordering of the fields in the string without changing the call to format():

result = "{1} says: 'Hello my name is {0}'".format(name, speaker)

Format is really powerful. You can use it to decide how wide to make a field, how to write numbers, and other formatting of the sort, depending on what you write inside the brackets.

You could also use the str.replace() function, or regular expressions (from the re module) if the replacements are more complicated.

11

Checkout the replace() function in python. Here is a link:

http://www.tutorialspoint.com/python/string_replace.htm

This should be useful when trying to replace some text that you have specified. For example, in the link they show you this:

str = "this is string example....wow!!! this is really string"
print str.replace("is", "was")

For every word "is", it would replace it with the word "was".

1
  • 3
    This is actually a good example of why str.replace is not what the OP wants: “this” will become “thwas” :) (please no unneeded semicolons thanks)
    – merwok
    May 29, 2013 at 1:08
8

Actually this is already implemented in the module string.Template.

5

You can do something like:

"My name is {name}".format(name="Name")

It's supported natively in python, as you can see here:

http://www.python.org/dev/peps/pep-3101/

2

You may also use formatting with % but .format() is considered more modern.

>>> "Your name is %(name)s. age: %(age)i" % {'name' : 'tom', 'age': 3}
'Your name is tom'

but it also supports some type checking as known from usual % formatting:

>>> '%(x)i' % {'x': 'string'}

Traceback (most recent call last):
  File "<pyshell#40>", line 1, in <module>
    '%(x)i' % {'x': 'string'}
TypeError: %d format: a number is required, not str

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.