Python string replace occurrence

Python replace string

Python replace string tutorial shows how to replace strings in Python.

  • replace method
  • re.sub method
  • translate method
  • string slicing and formatting

Python replace string with replace method

The replace method return a copys of the string with all occurrences of substring old replaced by new.

  • old − old substring to be replaced
  • new − new substring to replace old substring.
  • count − the optional count argument determines how many occurrences are replaced
#!/usr/bin/python msg = "There is a fox in the forest. The fox has red fur." msg2 = msg.replace('fox', 'wolf') print(msg2)

In the example, both occurrences of word ‘fox’ are replaced with ‘wolf’.

$ ./replacing.py There is a wolf in the forest. The wolf has red fur.

Alternatively, we can use the str.replace method. It takes the string on which we do replacement as the first parameter.

#!/usr/bin/python msg = "There is a fox in the forest. The fox has red fur." msg2 = str.replace(msg, 'fox', 'wolf') print(msg2)

The example is equivalent to the previous one.

Читайте также:  Решение задач на одномерные массивы в питоне

In the next example, we have a CSV string.

#!/usr/bin/python data = "1,2,3,4,5,6,7,8,9,10" data2 = data.replace(',', '\n') print(data2)

The replace each comma with a newline character.

$ ./replacing3.py 1 2 3 4 5 6 7 8 9 10 $ ./replacing3.py | awk ' < sum+=$1>END ' 55

Python replace first occurrence of string

The count parameter can be used to replace only the first occurrence of the given word.

#!/usr/bin/python msg = "There is a fox in the forest. The fox has red fur." msg2 = msg.replace('fox', 'wolf', 1) print(msg2)

The example replaces the first occurrence of the word ‘fox’.

$ ./replace_first.py There is a wolf in the forest. The fox has red fur.

Python replace last occurrence of string

In the next example, we replace the last occurrence of word ‘fox’.

#!/usr/bin/python msg = "There is a fox in the forest. The fox has red fur." oword = 'fox' nword = 'wolf' n = len(nword) idx = msg.rfind(oword) idx2 = idx + n - 1 print(f'')

We find the index of the last ‘fox’ word present in the message utilizing rfind method. We build a new string by omitting the old word an placing a new word there instead. We use string slicing and formatting operations.

$ ./replace_last.py There is a fox in the forest. The wolf has red fur.

Python chaining of replace methods

It is possible to chain the replace methods to do multiple replacements.

#!/usr/bin/python msg = "There is a fox in the forest. The fox has red fur." msg2 = msg.replace('fox', 'wolf').replace('red', 'brown').replace('fur', 'legs') print(msg2)

In the example, we perform three replacements.

$ ./chaining.py There is a wolf in the forest. The wolf has brown legs.

Python replace characters with translate

The translate method allows to replace multiple characters specified in the dictionary.

#!/usr/bin/python msg = "There is a fox in the forest. The fox has red fur." print(msg.translate(str.maketrans()))

We replace the dot characters with the exclamation marks in the example.

$ ./translating.py There is a fox in the forest! The fox has red fur!

Python replace string with re.sub

We can use regular expressions to replace strings.

re.sub(pattern, repl, string, count=0, flags=0)

The re.sub method returns the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl.

The Battle of Thermopylae was fought between an alliance of Greek city-states, led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the course of three days, during the second Persian invasion of Greece.

We have a small text file.

#!/usr/bin/python import re filename = 'thermopylae.txt' with open(filename) as f: text = f.read() cleaned = re.sub('[\.,]', '', text) words = set(cleaned.split()) for word in words: print(word)

We read the text file and use the re.sub method to remove the punctunation characters. We split the text into words and use the set function to get unique words.

In our case, we only have a dot and comma punctunation characters in the file. We replace them with empty string thus removing them.

$ ./replace_reg.py city-states days was Empire and second of led Battle alliance Greece King Persian Leonidas during between course Thermopylae Sparta I over three by Xerxes invasion an Greek The fought the

In this tutorial we have replaced strings in Python.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

Источник

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.

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

Источник

How to replace all occurrences of a character in a Python string

Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.

Overview

In Python, we can replace all occurrences of a character in a string using the following methods:

The replace() method

replace() is a built-in method in Python that replaces all the occurrences of the old character with the new character.

Syntax

"".replace(oldCharacter, newCharacter, count)

Parameters

This method accepts the following parameters:

  • oldCharacter : This is the old character that will be replaced.
  • newCharacter : This is the new character that will replace the old character.
  • count : This is an optional parameter that specifies the number of times to replace the old character with the new character.

Return value

This method creates a copy of the original string, replaces all the occurrences of the old character with the new character, and returns it.

Example

string = "This is an example string"
# replace all the occurrences of "i" with "I"
result = string.replace("i", "I")
# print result
print(result)

Explanation

  • Line 1: We declare a string.
  • Line 4: We use the replace() method to replace all the occurrences of i with I .
  • Line 7: We print the result to the console.

Output

In the output, we can see all the occurrences of i in the string are replaced with I .

The re.sub() method

We can also use regular expressions to replace all the occurrences of a character in a string. This can be done using re.sub() method.

Источник

Python String replace() Method

The replace() method replaces a specified phrase with another specified phrase.

Note: All occurrences of the specified phrase will be replaced, if nothing else is specified.

Syntax

Parameter Values

Parameter Description
oldvalue Required. The string to search for
newvalue Required. The string to replace the old value with
count Optional. A number specifying how many occurrences of the old value you want to replace. Default is all occurrences

More Examples

Example

Replace all occurrence of the word «one»:

txt = «one one was a race horse, two two was one too.»

Example

Replace the two first occurrence of the word «one»:

txt = «one one was a race horse, two two was one too.»

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

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