close

How to Replace Multiple Characters in a String in Python

Hello guys. How are you? I hope you all fine. In this tutorial we will learn about how to Replace Multiple Characters in a String in Python by the different methods. So without of wasting time lets start with the below methods.

How to Replace Multiple Characters in a String in Python

  1. Replace Multiple Characters in a String in Python

    To Replace Multiple Characters in a String in Python Use replace() You can replace Multiple Characters in a String in Python by using replace()function. This will replace the words from your string as you want. So lets learn this by given example:str1 = "I love dogs, dogs are loyal" str2 = str1.replace("dogs", "cats") print(str2) Output :I love cats, cats are loyal

  2. How to Replace Multiple Characters in a String in Python

    To Replace Multiple Characters in a String in Python Use dictionary In this method by making dictionary you can replace the words which you don't want in your string. lets learn about this method by given example:
    str1 = "I love dogs; dogs are loyal" var1 = {'love': 'like','dogs': 'cats',';':','} for Key,value in var1.items(): str1 = str1.replace(Key,value) print(str1)Output : I like cats, cats are loyal

Method 1 : Using replace()

You can replace Multiple Characters in a String in Python by using replace()function. This will replace the words from your string as you want. So lets learn this by given example:

str1 = "I love dogs, dogs are loyal"
str2 = str1.replace("dogs", "cats")
print(str2)

Output :

I love cats, cats are loyal

Method 2 : Using dictionary

In this method by making dictionary you can replace the words which you don’t want in your string. lets learn about this method by given example:

str1 = "I love dogs; dogs are loyal"
var1 = {'love': 'like','dogs': 'cats',';':','}
for Key,value in var1.items():
    str1 = str1.replace(Key,value)
print(str1)

Output :

I like cats, cats are loyal

Method 3 : Using translate()

By using translate() you can replace Multiple Characters. you can better understand by given below example. so lets learn about of that.

var1  = "I love dogs"
var2 = var1.translate(str.maketrans("o","i"))
print(var2)

Output :

I live digs

Method 4 : Using re. sub()

By using re. sub() you can replace Multiple Characters in a String in Python. you can better understand by given below example. so lets learn about of that.

import re
mystr = "std-12:students = 50; std-11:students = 60"
def var1 (mystr):
  mystr = re.sub('[0-9]', 'X', mystr)
  print(mystr)
var1(mystr)

Output :

std-XX:students = XX; std-XX:students = XX

Conclusion

It’s all About this Tutorial. Hope all methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you?

Also, Read

Leave a Comment