Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing a substring of a string with Python

Tags:

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') 
like image 778
kwikness Avatar asked May 03 '12 17:05

kwikness


People also ask

How do you replace all instances of a substring in a string Python?

The easiest way to replace all occurrences of a given substring in a string is to use the replace() function. If needed, the standard library's re module provides a more diverse toolset that can be used for more niche problems like finding patterns and case-insensitive searches.

Which string method is used to replace substring by new string in Python?

The replace() method returns a copy of the string where the old substring is replaced with the new substring.


2 Answers

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

like image 167
Raymond Hettinger Avatar answered Oct 17 '22 06:10

Raymond Hettinger


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.

like image 42
QuantumOmega Avatar answered Oct 17 '22 06:10

QuantumOmega