Python replace all letters

Python : How to replace single or multiple characters in a string ?

In this article we will discuss how to replace single or multiple characters in a string in Python.

Python provides a str.replace() function i.e.

It returns a new string object that is a copy of existing string with replaced content. Also,

  • If count is not provides then it will return a string with all the occurrences of ‘old’, replaced with ‘new’ string.
  • If count parameter is passed then it will return a string with first ‘count’ occurrences of ‘old’ string replaced with ‘new’ string.

Let’s understand by examples,

Frequently Asked:

Replace all occurrences of given character / string in a string

Suppose we have a string i.e.

mainStr = "Hello, This is a sample string"

Now, lets replace all the occurrences of ‘s’ with ‘X’ i.e.

''' Replace all occurrences of given character or string in main string ''' otherStr = mainStr.replace('s' , 'X')

Contents of otherStr is as follows,

Hello, ThiX iX a Xample Xtring

As strings are immutable in Python, so we can not change its content. Therefore member functions like replace() returns a new string.
As we have not provided the count parameter in replace() function. So, it will replace all the occurrences of ‘s’ with ‘X’. But what if we want to replace only first few occurrences instead of all? Let’s see how to do that,

Replace first n occurrences of given character / sub string in a string

Suppose we have a string i.e.

mainStr = "Hello, This is a sample string"

Now, lets replace first 2 occurrences of ‘s’ with ‘XXXS’ i.e.

''' Replace First 2 occurrences of given character or string in main string ''' otherStr = mainStr.replace('s' , 'XXXS', 2)

Contents of otherStr is as follows,

Hello, ThiXXXS iXXXS a sample string

As we have passed the count parameter as 2, so only first 2 occurrences of ‘s’ will be replaced in the returned copy.

Читайте также:  Php after function call

Replace multiple characters/strings in a string

str.replace() function can replace the occurrences of one given sub string only. But what if we want to replace multiple sub strings in a given string ?

Suppose we have a string i.e.

mainStr = "Hello, This is a sample string"

Now, how to replace all the occurrences of these three characters ‘s’, ‘l’, ‘a’ with this string ‘AA’ ?
Let’s create a new function over replace() to do that i.e.

''' Replace a set of multiple sub strings with a new string in main string. ''' def replaceMultiple(mainString, toBeReplaces, newString): # Iterate over the strings to be replaced for elem in toBeReplaces : # Check if string is in the main string if elem in mainString : # Replace the string mainString = mainString.replace(elem, newString) return mainString

It will replace all the occurrences of strings in List toBeReplaces with newString in the main given list mainString.
Let’s see how to replace the occurrences of [‘s’, ‘l’, ‘a’] with “AA” i.e.

''' Replace multiple characters / strings from a string ''' # Replace all the occurrences of string in list by AA in the main list otherStr = replaceMultiple(mainStr, ['s', 'l', 'a'] , "AA")

Contents of otherStr is as follows,

HeAAAAo, ThiAA iAA AA AAAAmpAAe AAtring

Complete example is as follows,

''' Replace a set of multiple sub strings with a new string in main string. ''' def replaceMultiple(mainString, toBeReplaces, newString): # Iterate over the strings to be replaced for elem in toBeReplaces : # Check if string is in the main string if elem in mainString : # Replace the string mainString = mainString.replace(elem, newString) return mainString def main(): mainStr = "Hello, This is a sample string" ''' Replace all occurrences of given character or string in main string ''' otherStr = mainStr.replace('s' , 'X') print("String with replaced Content : " , otherStr) ''' Replace First 2 occurrences of given character or string in main string ''' otherStr = mainStr.replace('s' , 'XXXS', 2) print(otherStr) ''' Replace multiple characters / strings from a string ''' # Replace all the occurrences of string in list by AA in the main list otherStr = replaceMultiple(mainStr, ['s', 'l', 'a'] , "AA") print(otherStr) if __name__ == '__main__': main()
String with replaced Content : Hello, ThiX iX a Xample Xtring Hello, ThiXXXS iXXXS a sample string HeAAAAo, ThiAA iAA AA AAAAmpAAe AAtring

Источник

Читайте также:  Detail of html language

How to replace all occurrences of a string with another string in Python?

A string is a group of characters that may be used to represent a single word or an entire phrase. In Python strings not require explicit declaration and may be defined with or without a specifier therefore, it is easy to use them.

Python has various built in functions and methods for manipulating and accessing strings. Because everything in Python is an object, a string is an object of the String class, which has several methods.

In this article, we are going to focus on replacing all occurrences of a string with another string in python.

Using the replace() method

The replace() method of string class accepts a string value as input and returns the modified string as output. It has 2 mandatory parameters and 1 optional parameter. Following is the syntax of this method.

string.replace(oldvalue, newvalue, count)
  • Old value − The substring that you want to replace.
  • New value − This represents the substring with which you want to replace.
  • Count − This is an optional parameter; it is used to specify the number of old values you want to replace with new values.

Example 1

In the program given below, we are taking an input string and by using the replace method we are replacing the letter “t” with “d”.

str1 = "Welcome to tutorialspoint" print("The given string is") print(str1) print("After replacing t with d") print(str1.replace("t","d"))

Output

The output of the above program is,

The given string is Welcome to tutorialspoint After replacing t with d Welcome do dudorialspoind

Example 2

In the program given below, we are taking the same input string and we are replacing the letter “t” with “d” using the replace() method, but in this example we are taking the count parameter as 2. So only 2 appearances of t are converted.

str1 = "Welcome to tutorialspoint" print("The given string is") print(str1) print("After replacing t with d for 2 times") print(str1.replace("t","d",2))

Output

The output of the above program is,

The given string is Welcome to tutorialspoint After replacing t with d for 2 times Welcome do dutorialspoint

Using the regular expressions

We can also use Python regular expressions to replace all occurrences of a string with another string. The sub() method of python re replaces an existing letter in the given string with a new letter. Following is the syntax of this method −

  • Old − The sub string that you want to replace.
  • New − The new sub string with which you want to replace.
  • String − The source string.
Читайте также:  Html reference php variable

Example

In the example given below, we are using the sub method of re library for replacing the letter “t” with “d”.

import re str1 = "Welcome to tutorialspoint" print("The given string is") print(str1) print("After replacing t with d ") print(re.sub("t","d",str1))

Output

The output of the above given program is,

The given string is Welcome to tutorialspoint After replacing t with d Welcome do dudorialspoind

Traversing through each character

Another approach is the brute force approach where you traverse each character of a particular string and check it with the character you want to replace, if it matches then replace that character else move forward.

Example

In the example given below, we are iterating over the string and matching each character and replacing them.

str1= "Welcome to tutorialspoint" new_str = '' for i in str1: if(i == 't'): new_str += 'd' else: new_str += i print("The original string is") print(str1) print("The string after replacing t with d ") print(new_str)

Output

The output of the above program is,

The original string is Welcome to tutorialspoint The string after replacing t with d Welcome do dudorialspoind

Источник

Оцените статью