How do you replace a variable in a string in python?

In this tutorial, we will learn about the Python replace() method with the help of examples.

The replace() method replaces each matching occurrence of the old character/text in the string with the new character/text.

Example

text = 'bat ball'

# replace b with c replaced_text = text.replace('b', 'c')

print(replaced_text) # Output: cat call


replace() Syntax

It's syntax is:

str.replace(old, new [, count]) 

replace() Parameters

The replace() method can take maximum of 3 parameters:

  • old - old substring you want to replace
  • new - new substring which will replace the old substring
  • count (optional) - the number of times you want to replace the old substring with the new substring

Note: If count is not specified, the replace() method replaces all occurrences of the old substring with the new substring.


replace() Return Value

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

If the old substring is not found, it returns the copy of the original string.


Example 1: Using replace()

song = 'cold, cold heart'

# replacing 'cold' with 'hurt' print(song.replace('cold', 'hurt'))

song = 'Let it be, let it be, let it be, let it be'

# replacing only two occurences of 'let' print(song.replace('let', "don't let", 2))

Output

hurt, hurt heart
Let it be, don't let it be, don't let it be, let it be

More Examples on String replace()

song = 'cold, cold heart'

replaced_song = song.replace('o', 'e')

# The original string is unchanged print('Original string:', song) print('Replaced string:', replaced_song) song = 'let it be, let it be, let it be' # maximum of 0 substring is replaced # returns copy of the original string

print(song.replace('let', 'so', 0))

Output

Original string: cold, cold heart
Replaced string: celd, celd heart
let it be, let it be, let it be

I'm trying to maintain/update/rewrite/fix a bit of Python that looks a bit like this:

variable = """My name is %s and it has been %s since I was born.
              My parents decided to call me %s because they thought %s was a nice name.
              %s is the same as %s.""" % (name, name, name, name, name, name)

There are little snippets that look like this all over the script, and I was wondering whether there's a simpler (more Pythonic?) way to write this code. I've found one instance of this that replaces the same variable about 30 times, and it just feels ugly.

Is the only way around the (in my opinion) ugliness to split it up into lots of little bits?

variable = """My name is %s and it has been %s since I was born.""" % (name, name)
variable += """My parents decided to call me %s because they thought %s was a nice name.""" % (name, name)
variable += """%s is the same as %s.""" % (name, name)

mdeous

16.9k7 gold badges55 silver badges59 bronze badges

asked Aug 8, 2011 at 13:36

Use a dictionary instead.

var = '%(foo)s %(foo)s %(foo)s' % { 'foo': 'look_at_me_three_times' }

Or format with explicit numbering.

var = '{0} {0} {0}'.format('look_at_meeee')

Well, or format with named parameters.

var = '{foo} {foo} {foo}'.format(foo = 'python you so crazy')

answered Aug 8, 2011 at 13:39

Cat Plus PlusCat Plus Plus

122k26 gold badges195 silver badges222 bronze badges

1

Use formatting strings:

>>> variable = """My name is {name} and it has been {name} since..."""
>>> n = "alex"
>>>
>>> variable.format(name=n)
'My name is alex and it has been alex since...'

The text within the {} can be a descriptor or an index value.

Another fancy trick is to use a dictionary to define multiple variables in combination with the ** operator.

>>> values = {"name": "alex", "color": "red"}
>>> """My name is {name} and my favorite color is {color}""".format(**values)
'My name is alex and my favorite color is red'
>>>

answered Aug 8, 2011 at 13:47

How do you replace a variable in a string in python?

monkutmonkut

40.3k23 gold badges118 silver badges148 bronze badges

1

Python 3.6 has introduced a simpler way to format strings. You can get details about it in PEP 498

>>> name = "Sam"
>>> age = 30
>>> f"Hello, {name}. You are {age}."
'Hello, Sam. You are 30.'

It also support runtime evaluation

>>>f"{2 * 30}"
'60'

It supports dictionary operation too

>>> comedian = {'name': 'Tom', 'age': 30}
>>> f"The comedian is {comedian['name']}, aged {comedian['age']}."
 The comedian is Tom, aged 30.

answered Jun 22, 2019 at 5:22

How do you replace a variable in a string in python?

Arghya SahaArghya Saha

5,3314 gold badges24 silver badges43 bronze badges

Use the new string.format:

name = 'Alex'
variable = """My name is {0} and it has been {0} since I was born.
          My parents decided to call me {0} because they thought {0} was a nice name.
          {0} is the same as {0}.""".format(name)

answered Aug 8, 2011 at 13:39

Zaur NasibovZaur Nasibov

21.8k11 gold badges51 silver badges80 bronze badges

>>> "%(name)s %(name)s hello!" % dict(name='foo')
'foo foo hello!'

answered Aug 8, 2011 at 13:39

Mikhail KorobovMikhail Korobov

21.5k8 gold badges72 silver badges64 bronze badges

You could use named parameters. See examples here

answered Aug 8, 2011 at 13:38

How do you replace a variable in a string in python?

J0HNJ0HN

25.4k5 gold badges50 silver badges84 bronze badges

variable = """My name is {0} and it has been {0} since I was born.
              My parents decided to call me {0} because they thought {0} was a nice name.
              {0} is the same as {0}.""".format(name)

answered Aug 8, 2011 at 13:39

xubuntixxubuntix

2,32518 silver badges19 bronze badges

answered Aug 8, 2011 at 13:38

How do you replace a variable in a string in python?

GryphiusGryphius

72.6k6 gold badges47 silver badges53 bronze badges

If you are using Python 3, than you can also leverage, f-strings

myname = "Test"
sample_string = "Hi my name is {name}".format(name=myname)

to

sample_string = f"Hi my name is {myname}"

answered Feb 28, 2020 at 13:35

How do you replace a value in a string?

Java String replace(char old, char new) method example.
public class ReplaceExample1{.
public static void main(String args[]){.
String s1="javatpoint is a very good website";.
String replaceString=s1.replace('a','e');//replaces all occurrences of 'a' to 'e'.
System.out.println(replaceString);.

How do you replace one character in a string in Python?

replace() method helps to replace the occurrence of the given old character with the new character or substring. The method contains the parameters like old(a character that you wish to replace), new(a new character you would like to replace with), and count(a number of times you want to replace the character).

How do you replace specific text in Python?

replace() method returns a copy of a string..
old_text is the first required parameter that . replace() accepts. It's the old character or text that you want to replace. ... .
new_text is the second required parameter that . replace() accepts. ... .
count is the optional third parameter that . replace() accepts..

How do you replace a number in a string in Python?

Method #1 : Using replace() + isdigit() In this, we check for numerics using isdigit() and replace() is used to perform the task of replacing the numbers by K.