Replacing a substring of a string with Python Replacing a substring of a string with Python python python

Replacing a substring of a string with Python


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


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.


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