replace a string containing a substring with a string in Python

python replace character in string at index
python string replace regex
string replace python
python regex replace multiple patterns
python replace multiple characters in string
python string replace multiple
python substring
python 3 string replace

I need to replace a string containing a substring with another string. For example:

biography -> biography
biographical -> biography
biopic -> biography
bio-pic -> biography-pic
I watched a biographical movie -> I watched a biography movie

Here, all words on the left contain bio, so the whole word is replaced by biography. I am aware of string.replace() function, but it doesn't seem to work well here. I looked up regular expressions, but I'm not sure if re is the right library to solve the problem.

Using Regex

import re

s = """
biography -> biography
biographical -> biography
biopic -> biography
bio-pic -> biography-pic
I watched a biographical movie -> I watched a biography movie
"""
x = re.sub(r'\b(bio\w*)', 'biography', s)
print(x)

Output

biography -> biography
biography -> biography
biography -> biography
biography-pic -> biography-pic
I watched a biography movie -> I watched a biography movie

Python String replace() Method, new − This is new substring, which would replace old substring. max − If this optional argument max is given, only the first count occurrences are replaced. Here the replacement of a substring in list of string is performed. Let’s discuss certain ways in which this can be performed. Method #1 : Using list comprehension + replace () The replace method can be coupled with the list comprehension technique to achieve this particular task.

import re

search_string = 'bio'
replace_string = 'biography'
vals = ['biography', 'biographical', 'biopic', 'bio-pic', 'something else', 'bio pic', 'I watched a biographical movie']
altered = [re.sub(re.escape(search_string)+r'\w*',replace_string,val) for val in vals]
print(altered)

outputs

['biography', 'biography', 'biography', 'biography-pic', 'something else', 'biography pic', 'I watched a biography movie']

For the regex part, re.escape() can be used to turn a variable into a regular expression. I assumed your 'bio' search string will not be constant. The rest of it \w* means to match 0 or more (the *) of the preceding character. \w means word characters (a-z, A-Z, 0-9, and _). Since we're only matching word characters, it stops the match when a space is encountered.

replace() in Python to replace a substring, Given a string str that may contain one more occurrences of “AB”. Replace all occurrences of “AB” with “C” in str. Examples: Input : str� Python string method replace() returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to max. Syntax. Following is the syntax for replace() method − str.replace(old, new[, max]) Parameters. old − This is old substring to be replaced.

Try regular expression to solve this problem. It will definitely. You can change regular expression according to your requirement. Here is an example code

import re
s = "biography biographical biopic bio-pic I watched a biographical movie"
replaced = re.sub('(bio[A-Za-z]*)', 'biography', s)
print (replaced )

Python, It contains well written, well thought and well explained computer science Here the replacement of a substring in list of string is performed. Python offers many ways to substring a string. It is often called ‘slicing’. It follows this template: string[start: end: step] Where, start: The starting index of the substring. The character at this index is included in the substring. If start is not included, it is assumed to equal to 0. end: The terminating index of the substring.

One of the decisions:

import re

def f(s, pat, replace):
    pat = r'(\w*%s\w*)' % pat
    return re.sub(pat, "biography", s)

input = """
biography -> biography
biographical -> biography
biopic -> biography
bio-pic -> biography-pic
I watched a biographical movie -> I watched a biography movie
"""

c = f(input, "bio", "biography")
print(c)

Output:

biography -> biography
biography -> biography
biography -> biography
biography-pic -> biography-pic
I watched a biography movie -> I watched a biography movie

Replace strings in Python (replace, translate, re.sub, re.subn), Replace multiple substrings with the same string; Replace using the It just calls replace() in order, so if the first new contains the following old� Python String | replace () replace () is an inbuilt function in Python programming language that returns a copy of the string where all occurrences of a substring is replaced with another substring.

String Manipulation and Regular Expressions, With this, let's take a quick tour of some of Python's string manipulation tools. and replace a given substring with a new string, you can use the replace() method. can include format codes which control how the value is converted to a string. In this article, we'll examine four ways to use Python to check whether a string contains a substring. Each has their own use-cases and pros/cons, some of which we'll briefly cover here: 1) The in Operator The easiest way to check if a Python string contains a substring is to use the in operator. The in operator is used to check data structures for membership in Python. It returns a Boolean

Using Regex for Text Manipulation in Python, In the output, null will be returned since the text string doesn't contain "1998" directly at the start. Now let's change the content text variable and add "1998" at the� Replace a substring of a column in pandas python can be done by replace() funtion. Let’s see how to Replace a substring with another substring in pandas; Replace a pattern of substring with another substring using regular expression; With examples. First let’s create a dataframe

How to Check if a String contains a Substring in Python?, How to use Python Raw Strings? Using Python String format_map() � How to use the Python center() method? Python String isprintable() � Python replace()� 3. The replace method. The built-in replace method is used to replace the occurrences of a specific substring inside a string with another value. It returns another copy of the original string by replacing all occurrences of a specific substring with the specified value (or substring).

Comments
  • doesn't seem to work well here? What do you mean by that?
  • @SukumarRdjf Good question, I suspect that the problem is that it maps biography to biographygraphy
  • First split string to words then apply suggestion of @SubhrajyotiDas to each word.
  • @Sukumar-Rdjf I mean that I don't want to construct the dictionary consisting of all possible words containing bio, and then call string.replace(word, bio) for every such word
  • Are you certain that you won't have things like 'biology' which have nothing to do with 'biography' but nevertheless contain 'bio'?