Use np.where

Ex:

import numpy as np

df['Target'] = np.where(df['Target'] == "U", df['Action'], df['Target'])
Answer from Rakesh on Stack Overflow
🌐
W3Schools
w3schools.com › python › ref_string_replace.asp
Python String replace() Method
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, if nothing else is specified....
Discussions

python - replace item in a string if it matches an item in the list - Stack Overflow
I am trying to remove words from a string if they match a list. x = "How I Met Your Mother 7x17 (HDTV-LOL) [VTV] - Mon, 20 Feb 2012" tags = ['HDTV', 'LOL', 'VTV', 'x264', 'DIMENSION', 'XviD', '72... More on stackoverflow.com
🌐 stackoverflow.com
python - how to replace if statements in a for loop (for better looking code) - Stack Overflow
I'd like to remove repetitive code but I'm stuck. I want the for loop to iterate through a list and append the object to another list depending on if the list has "red","blue",or & More on stackoverflow.com
🌐 stackoverflow.com
Trying to replace input string with another string with multiple conditions
Python noob here! I’m trying to replace an input string with another string, depending on which condition is met. My problem is that it only works when the first condition is met. When I run the program it prompts me for an input of A, B, C, D or E. If I enter “a” or “A” the string ... More on discuss.python.org
🌐 discuss.python.org
6
0
March 18, 2022
python string replace using for loop with if else - Stack Overflow
I am new with python, trying to replace string using for loop with if else condition, I have a string and want to replace some character of that string in a such way that it should take / pick first More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 2
2

A defaultdict can be very helpful here. The defaultdict enables the creation of the specified dict-key-object (list) if it does not already exist, or uses the existing object's methods if it does exist.

On first iteration, the dict is empty, but the list.append method can be called on the 'empty' key, as the default object of the dict is a list. This SO post goes into greater detail.

For example:

from collections import defaultdict

sublist = ['green', 'red', 'red', 'red', 'blue', 'blue', 'green']

d = defaultdict(list)
for i in sublist:
    d[i].append(i)

Output:

defaultdict(list,
            {'green': ['green', 'green'],
             'red': ['red', 'red', 'red'],
             'blue': ['blue', 'blue']})

Which can be accessed just like a builtin dict:

>>> d['green']
['green', 'green'] 

Or, explicitly converted into a builtin dict:

>>> dict(d)
{'green': ['green', 'green'],
 'red': ['red', 'red', 'red'],
 'blue': ['blue', 'blue']}  

Removing unwanted items

If the source list contains unwanted items, they can be removed as shown below.

The complete code:

from collections import defaultdict

sublist = ['green', 'red', 'red', 'red', 'blue', 'blue', 'green',
           None, 'Sam', 'Bob', 'Sue', None, None]

# Append items to dict key/items.
d = defaultdict(list)
for i in sublist:
    d[i].append(i)

# Define a list of items to be kept.
keep = ['blue', 'red', 'green']

# Iterate a *copy* of the dict and pop the unwanted items.
for k in d.copy():
    if k not in keep:
        d.pop(k)

Output:

defaultdict(list,
            {'green': ['green', 'green'],
             'red': ['red', 'red', 'red'],
             'blue': ['blue', 'blue']})
2 of 2
0

You could do something like this? (untested)

colors = ['red', 'blue', 'green']
lists = {color: [] for color in colors}
    
for color, list_ in lists.items():
    for item in sublist:
        if color in sublist:
            list_.append(item)
    lists[color] = list(filter(None, list_).remove(color)
🌐
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 ...
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.replace.html
pandas.DataFrame.replace — pandas 3.0.6 documentation
Value to replace any values matching to_replace with. For a DataFrame a dict of values can be used to specify which value to use for each column (columns not in the dict will not be filled). Regular expressions, strings and lists or dicts of such objects are also allowed. ... If True, performs operation inplace.
🌐
Note.nkmk.me
note.nkmk.me › home › python
Replace Strings in Python: replace(), translate(), and Regex | note.nkmk.me
May 4, 2025 - To replace multiple different substrings with the same value, regular expressions are useful (see below). If replacing different substrings with different values, apply replace() repeatedly.
Find elsewhere
🌐
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 ...
🌐
Python.org
discuss.python.org › python help
Trying to replace input string with another string with multiple conditions - Python Help - Discussions on Python.org
March 18, 2022 - Python noob here! I’m trying to replace an input string with another string, depending on which condition is met. My problem is that it only works when the first condition is met. When I run the program it prompts me for an input of A, B, C, D or E. If I enter “a” or “A” the string ...
🌐
Real Python
realpython.com › replace-string-python
How to Replace a String in Python – Real Python
October 22, 2025 - Loading the transcript as a triple-quoted string and then using the .replace() method on one of the swear words works fine. But there’s another swear word that’s not getting replaced because in Python, the string needs to match exactly: ... As you can see, even if the casing of one letter ...
🌐
Analytics Vidhya
analyticsvidhya.com › home › beginner’s guide to replace() method in python
Beginner’s Guide to replace() Method in Python
April 15, 2024 - While `replace()` is versatile, it’s important to handle edge cases. What if the `old` string isn’t found? Or what if `count` is set to a number greater than the occurrences of `old`? Python handles these gracefully: if `old` isn’t found, the original string is returned unchanged, and if `count` exceeds the number of occurrences, all instances of `old` are replaced.
🌐
AskPython
askpython.com › python › string › python-replace-function
Python replace() function - AskPython
2 days ago - Python strings are immutable, so replace() returns a result instead of changing the original string. Assign that result back to the same name if later code should use the changed text.
🌐
Reddit
reddit.com › r/learnpython › replacing if else function trees with dictionaries of functions: am i trying too hard?
r/learnpython on Reddit: Replacing if else function trees with dictionaries of functions: Am I trying too hard?
January 28, 2024 -

My question is answered, however feel free to add more if you'd like =)

I've been improving my Python recently and figured I could replace these "function trees" with a function dictionary

job.get_job()
if job.status == enums.Status.SUCCESS:
    job.success()
elif job.status == enums.Status.NO_CONTENT:
    job.no_content()
elif job.status == enums.Status.FAILURE:
    job.failure()

turns into

handler = dict()
handler[enums.Status.SUCCESS] = job.success
handler[enums.Status.NO_CONTENT] = job.no_content
handler[enums.Status.FAILURE] = job.failure

job.get_job()
handler[job.status]()

In this case I don't need to pass any params, but when needed I use a lambda

It sure feels fancy, since this is new to me. But is it a good idea? Also open to other ideas.

Top answer
1 of 3
1

The string replace method does not replace characters by position, it replaces them by what characters they are.

>>> 'apple aardvark'.replace('a', '!')
'!pple !!rdv!rk'

So in your first case, you are telling to replace "hk" with "kh". It doesn't "know" that you want to only replace one of the occurrences; it just knows you want to replace "hk" with "kh", so it replaces all occurrences.

You can use the count argument to replace to specify that you only want to replace the first occurrence:

>>> go = 'USC_45774-1111-0     <hkxhk> {10} ; 78'
... go.replace(go[22:24],go[23:21:-1],1)
'USC_45774-1111-0     <khxhk> {10} ; 78'

Note, though, that this will always replace the first occurrence, not necessarily the occurrence at the position in the string you specified. In this case I guess that's what you want, but it may not work directly for other similar tasks. (That is, there is no way to use this method as-is to replace the second occurrence or the third occurrence; you can only replace the first, or the first two, or the first three, etc. To replace the second or third occurrence you'd need to do a bit more.)

As for the second part of your question, you are misunderstanding what if "{01}" or "{-1}" in line means. It means, in layman's terms, if "{01}" or if "{-1}" in line. Since if "{01}" is always true (i.e., the string "{01}" is not a false value), the whole condition is always true. What you want is if "{01}" in line or "{-1}" in line".

2 of 3
0

I don't know what it is about Python, but your problem is one that gets posted here at least a couple times every day.

if "{01}" or "{-1}" in line:

This doesn't do what you think it does. It asks, "is "{01}" true"? Because it's a non-zero-length string, it is. Because or short-circuits, the rest of the condition is not tested because the first argument is true. Therefore the body of your if statement is always executed.

In other words, Python evaluates as if you'd written this:

if ("{01}") or ("{-1}" in line):

You want something like:

if "{01}" in line or "{-1}" in line:

Or if you have a lot of similar conditions:

if any(x in line for x in ("{01}", "{-1}")):
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-replace-all-occurrences-of-a-substring-in-a-string
Python - Replace all Occurrences of a Substring in a String - GeeksforGeeks
August 13, 2026 - if s[i:i+len(target)] == target: Take a slice of the string from index i to i + len(target) and check if it matches the target substring. res += replacement If a match is found, append the replacement string to res.