You can use str.contains to mask the rows that contain 'ball' and then overwrite with the new value:

In [71]:
df.loc[df['sport'].str.contains('ball'), 'sport'] = 'ball sport'
df

Out[71]:
    name       sport
0    Bob      tennis
1   Jane  ball sport
2  Alice  ball sport

To make it case-insensitive pass `case=False:

df.loc[df['sport'].str.contains('ball', case=False), 'sport'] = 'ball sport'
Answer from EdChum on Stack Overflow
Discussions

python - Replacing string if it contains specified pattern - Stack Overflow
Well, if you plan to just match word chars, . and - in the user name part, you may use r'[\w.-]+@ongoose\.com\|'. BTW, ["|"] matches " or | ... Add the character you want to match in a character class [\w.-]. In you example you want to match piramal and in your regex you want to match ongoose. To match both of them you might use an alternation (?:ongoose|piramal) or match any non whitespace character using \S+ and replace with an empty string... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to replace a cell value if it contains a string? Pandas
Regex. You should be able to figure it out pretty quickly with some google. More on reddit.com
๐ŸŒ r/learnpython
2
1
July 15, 2015
Check if certain Strings are present in a Sentence and Replace them with another String using Python 3.6 - Stack Overflow
My program is to check if the input sentence contains not followed by bad and replace it with good. For instance if the sentence contained not bad without any other string in between not and bad, I... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Should I check if a substring exists before trying to replace it? - Stack Overflow
For the replace function, if the first argument (substring1) isnโ€™t found in the string, nothing will happen. So the second one is perfectly safe to use. Always remember that simpler is better. ... It depends on the expected workload. str.replace is several times slower than str.__contains__, so ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ ref_string_replace.asp
Python String replace() Method
Remove List Duplicates Reverse ... Study Plan Python Interview Q&A Python Training ... The replace() method replaces a specified phrase with another specified phrase. Note: All occurrences of the specified phrase will be replaced, ...
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ replace-occurrences-of-a-substring-in-string-with-python
Replace Occurrences of a Substring in String with Python
September 21, 2020 - The easiest way to replace all occurrences of a given substring in a string is to use the replace() function. If needed, the standard library's re module provides a more diverse toolset that can be used for more niche problems like finding patterns and case-insensitive searches.
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ python-string-contains
Python String Search and Replace: in, .find(), .index(), .count(), and .replace() | DataCamp
March 31, 2026 - Use the in operator for simple containment, .find() or .index() when you need positions, .count() for non-overlapping tallies, and .replace() for substitutions. Normalize with .casefold() for case-insensitive checks, and prefer dedicated prefix/suffix helpers when appropriate.
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
Replace Strings in Python: replace(), translate(), and Regex | note.nkmk.me
May 4, 2025 - Note that replacements occur in the order they are called. If a new substring contains another substring targeted later, it will also be replaced.
๐ŸŒ
IncludeHelp
includehelp.com โ€บ python โ€บ replace-whole-string-if-it-contains-substring-in-pandas.aspx
Python - Replace whole string if it contains substring in pandas
df.loc[df['stream'].str.contains('aths'), 'stream'] = 'Arts' ... # Importing pandas package import pandas as pd # Creating a dictionary with equal elements d = { 'student':['Aftab','Abhishek','Bhavna','Kartik','Rishi'], 'stream':['Commerce','Science','Maths','Maths','Arts'] } # Creating a DataFrame df = pd.DataFrame(d) # Display DataFrame print("Created DataFrame:\n",df) # Filtering and replacing Stream column df.loc[df['stream'].str.contains('aths'), 'stream'] = 'Arts' # Display modified DataFrame print("Modified DataFrame:\n",df)
Find elsewhere
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
Extract and Replace Elements That Meet the Conditions of a List of Strings in Python | note.nkmk.me
May 19, 2023 - To replace the whole element containing a specific string, use the in operator to extract it and apply conditional expressions (ternary operator), formatted as X if condition else Y. ... Use conditional expressions for the expression part of ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-string-replace
Python String replace() Method - GeeksforGeeks
October 28, 2024 - Hi Python!". Note: Since replace() creates a new string, the original string remains unchanged. ... count (optional): Specifies the maximum number of replacements to perform. If omitted, all occurrences are replaced.
๐ŸŒ
Real Python
realpython.com โ€บ replace-string-python
How to Replace a String in Python โ€“ Real Python
October 22, 2025 - Because you get this match object in the callback, you can use any of the information contained within it to build the replacement string.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 51379050 โ€บ replacing-string-if-it-contains-specified-pattern
python - Replacing string if it contains specified pattern - Stack Overflow
Well, if you plan to just match word chars, . and - in the user name part, you may use r'[\w.-]+@ongoose\.com\|'. BTW, ["|"] matches " or | ... Add the character you want to match in a character class [\w.-]. In you example you want to match piramal and in your regex you want to match ongoose. To match both of them you might use an alternation (?:ongoose|piramal) or match any non whitespace character using \S+ and replace with an empty string...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-replace-all-occurrences-of-a-substring-in-a-string
Python - Replace all occurrences of a substring in a string - GeeksforGeeks
January 8, 2025 - Replacing the Nth occurrence of multiple characters in a string with a given character involves identifying and counting specific character occurrences.Using a Loop and find()Using a loop and find() method allows us to search for the first occurrence of a substring within each list element. This app ยท 2 min read Python - Check if substring present in string
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ methods โ€บ string โ€บ replace
Python String replace()
The replace() method replaces each matching occurrence of a substring with another string. ... # replace 'ba' with 'ro' replaced_text = text.replace('ba', 'ro') print(replaced_text) # Output: rot roll ... Note: If count is not specified, the replace() method replaces all occurrences of the ...
๐ŸŒ
Cisco
ipcisco.com โ€บ home โ€บ python string contains
Python String Contains | Find | Index | Count | Replace โ‹† IpCisco
December 27, 2021 - It is the string that we are looking for. Beside this parameters, there is also a start and end parameter. These paramaters are the indexes that can be mentioned before this search. This means that look for between these indexes if Python String Contains it or not.
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.Series.str.replace.html
pandas.Series.str.replace โ€” pandas 3.0.6 documentation
Dictionary contains <key : value> pairs of strings to be replaced along with the updated value. ... Replacement string or a callable. The callable is passed the regex match object and must return a replacement string to be used. Must have a value of None if pat is a dict See re.sub().
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to replace a cell value if it contains a string? pandas
r/learnpython on Reddit: How to replace a cell value if it contains a string? Pandas
July 15, 2015 -

I have a DataFrame where customers entered their job title's manually instead of from a drop down menu so now I have what could be 50 different ways to describe "Director". I want to replace any cell value with "Director" if that cell contains the string "Director". So it could be "Senior Director Engineering Design" or "Director of R&D" etc but I want to rename them all "Director".

Top answer
1 of 2
2
import re
s = 'The day is  at not all bad'
pattern=r'(not)(?(1).+(bad))'

match=re.search(pattern,s)

new_string=re.sub(pattern,"good",s)

print(new_string)

output:

The day is  at good

Regex explanation :

I used if else condition regex here :

How if else in regex works , well this is very simple if else regex syntax:

(condition1)(?(1)(do something else))
(?(A)X|Y)

This means "if proposition A is true, then match pattern X; otherwise, match pattern Y."

so in this regex :

(not)(?(1).+(bad))

it matches 'bad' if 'not' in the string, the condition is 'not' must present in the string.

Second Regex :

if you want you can also use this regex:

(not.+)(bad)

In this group(2) is matching 'bad'.

Your string :

>>> s = 'The day is not at all bad' #input

>>> print(output)
>>> 'The day is good' # output
2 of 2
1

There are a couple of ways you could approach this. One way is to convert the sentence to a list of words, locate "not" and "bad" in the list, remove them and all the elements in between and then insert "good".

>>> s = 'the day is not at all bad'
>>> start, stop = 'not', 'bad'
>>> words = s.split()
>>> words
['the', 'day', 'is', 'not', 'at', 'all', 'bad']
>>> words.index(start)
3
>>> words.index(stop)
6
>>> del words[3:7]  # add 1 to stop index to delete "bad"
>>> words
['the', 'day', 'is']
>>> words.insert(3, 'good')
>>> words
['the', 'day', 'is', 'good']
>>> output = ' '.join(words)
>>> print(output)
the day is good

Another method is to use regular expressions to find a pattern that matches "not" followed by zero or more words, followed by "bad". The re.sub function finds strings that match a given pattern and replaces them with a string that you provide:

>>> import re
>>> pattern = r'not\w+bad'
>>> re.search(pattern, s)
>>> pattern = r'not(\s+\w+)* bad' # pattern matches "not <words> bad" 
>>> re.sub(pattern, 'good', s)
'the day is good'
๐ŸŒ
AskPython
askpython.com โ€บ python โ€บ string โ€บ python-replace-function
Python replace() function - AskPython
2 days ago - Assign that result back to the same name if later code should use the changed text. Call replace() on the string that contains the text you want to change, then pass the exact substring and its replacement.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ python-string-replace-function-in-python-for-substring-substitution
Python String.Replace() โ€“ Function in Python for Substring Substitution
January 24, 2022 - When using the .replace() Python method, you are able to replace every instance of one specific character with a new one. You can even replace a whole string of text with a new line of text that you specify.