Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python replace function [replace once]

Tags:

I need help with a program I'm making in Python.

Assume I wanted to replace every instance of the word "steak" to "ghost" (just go with it...) but I also wanted to replace every instance of the word "ghost" to "steak" at the same time. The following code does not work:

 s="The scary ghost ordered an expensive steak"  print s  s=s.replace("steak","ghost")  s=s.replace("ghost","steak")  print s 

it prints: The scary steak ordered an expensive steak

What I'm trying to get is The scary steak ordered an expensive ghost

like image 887
user2154113 Avatar asked Mar 10 '13 15:03

user2154113


People also ask

How do you replace only once in Python?

It replaces the count number of occurrences of given substring with the replacement string. A string is immutable in Python, therefore the replace() function returns a copy of the string with modified content. To replace only first occurrence of “is” with “XX”, pass the count value as 1.

Does replace in Python replace all?

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

How do you do multiple replace in Python?

Use the translate() method to replace multiple different characters. You can create the translation table specified in translate() by the str. maketrans() . Specify a dictionary whose key is the old character and whose value is the new string in the str.

What does replace () mean in Python?

replace() is an inbuilt function in the Python programming language that returns a copy of the string where all occurrences of a substring are replaced with another substring. Syntax : string.replace(old, new, count)


1 Answers

I'd probably use a regex here:

>>> import re >>> s = "The scary ghost ordered an expensive steak" >>> sub_dict = {'ghost':'steak','steak':'ghost'} >>> regex = '|'.join(sub_dict) >>> re.sub(regex, lambda m: sub_dict[m.group()], s) 'The scary steak ordered an expensive ghost' 

Or, as a function which you can copy/paste:

import re def word_replace(replace_dict,s):     regex = '|'.join(replace_dict)     return re.sub(regex, lambda m: replace_dict[m.group()], s) 

Basically, I create a mapping of words that I want to replace with other words (sub_dict). I can create a regular expression from that mapping. In this case, the regular expression is "steak|ghost" (or "ghost|steak" -- order doesn't matter) and the regex engine does the rest of the work of finding non-overlapping sequences and replacing them accordingly.


Some possibly useful modifications

  • regex = '|'.join(map(re.escape,replace_dict)) -- Allows the regular expressions to have special regular expression syntax in them (like parenthesis). This escapes the special characters to make the regular expressions match the literal text.
  • regex = '|'.join(r'\b{0}\b'.format(x) for x in replace_dict) -- make sure that we don't match if one of our words is a substring in another word. In other words, change he to she but not the to tshe.
like image 94
mgilson Avatar answered Sep 29 '22 12:09

mgilson