I would suggest using replace along with map

Example:

my_list = ['BASE', 'BASE xBU xPY', 'BU GROUP REL', 'PY REL']
converter = lambda x: x.replace(' ', '_')
my_list = list(map(converter, my_list))
my_list
['BASE', 'BASE_xBU_xPY', 'BU_GROUP_REL', 'PY_REL']
Answer from Kuldeep Singh Sidhu on Stack Overflow
🌐
Stack Abuse
stackabuse.com › bytes › replace-underscores-with-spaces-in-python
Replace Underscores with Spaces in Python
July 1, 2022 - Here you can see how the split method creates a list out of the given string: >>> underscore_str = "hello_world" >>> underscore_str.split("_") ['hello', 'world']
🌐
Tutor Python
tutorpython.com › python-replace-space-with-underscore
Python Replace Space with Underscore - Tutor Python
October 19, 2023 - Python Replacing spaces with underscores is a common requirement while programming. In this article, we explored three different ways to achieve replace space with underscore: Using the replace() method, regular expressions, and list comprehension.
Discussions

python - How to replace whitespaces with underscore? - Stack Overflow
I want to replace whitespace with underscore in a string to create nice URLs. So that for example: ... I am using Python with Django. Can this be solved using regular expressions? ... How can this this be achieved in django template. Is there any way to remove white spaces. More on stackoverflow.com
🌐 stackoverflow.com
python - Fastest way to replace space for underscore for a list of words in text - Stack Overflow
Is there a way to replace all of the terms with spaces by the terms with underscore for each line? That will help in avoiding the inner loop. Would it be more efficient if index the text using something like whoosh first then query the index and replace the terms? I would still need something like a O(1*S) to do the replacements, right? The solution doesn't need to be in Python... More on stackoverflow.com
🌐 stackoverflow.com
modelbuilder - Replace occasional Space with Underscore using Python parser of ArcGIS Field Calculator? - Geographic Information Systems Stack Exchange
I am creating a model which will give me two string values, one which reads exactly what is in a field and another which automatically replaces any Space with an "_". I have used Calculate Value to... More on gis.stackexchange.com
🌐 gis.stackexchange.com
Replace space with underscore using python - Stack Overflow
1 Python3 - Replacing spaces with underscore, but skip first element · 2 Is there a way to substitute single spaces in a string with underscore (or any other symbol)? More on stackoverflow.com
🌐 stackoverflow.com
🌐
w3resource
w3resource.com › python-exercises › re › python-re-exercise-23.php
Python: Replace whitespaces with an underscore and vice versa - w3resource
Write a Python program to replace whitespaces with an underscore and vice versa. ... import re text = 'Python Exercises' text =text.replace (" ", "_") print(text) text =text.replace ("_", " ") print(text) ... Write a Python program to replace all spaces in a string with underscores and then convert underscores back to spaces.
🌐
Java2Blog
java2blog.com › home › python › python string › replace space with underscore in python
Replace space with underscore in Python [4 ways] - Java2Blog
January 22, 2022 - The for loop can iterate over a string in Python. In every iteration, we will compare the character with whitespace. If the match returns true, we will replace it with an underscore character. ... We iterate over the string s using the for loop. If the character is a space, we concatenate _ to string a.
🌐
CodeSpeedy
codespeedy.com › home › replace space with underscore in python
Replace space with underscore in Python - CodeSpeedy
November 9, 2022 - The string will be divided into a list based on white space, and these components will be joined using the join() method with the underscore character serving as the separator. ... In this instructional exercise, we examined how to supplant a space with a highlight in a string. The replace() and re.sub() capabilities end up being the clearest strategies.
Find elsewhere
🌐
Bobby Hadz
bobbyhadz.com › blog › python-replace-spaces-with-underscores
How to replace Spaces with Underscores in Python | bobbyhadz
Call the replace() method on the string. Pass a string containing a space and a string containing an underscore to the method.
🌐
Python Guides
pythonguides.com › replace-whitespaces-with-underscore-in-python
Python Replace Whitespaces With Underscore
August 25, 2025 - Another Pythonic way is to use the map() function with a small lambda expression. This is not the most common approach, but it’s a neat trick that I’ve used when working with functional-style code. ... # Example: Replace spaces with underscores using map() text = "Boston Housing Price Index" result = "".join(map(lambda x: "_" if x == " " else x, text)) print("Original:", text) print("Modified:", result)
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 best ways to replace spaces in a python string with a specific character
5 Best Ways to Replace Spaces in a Python String with a Specific Character - Be on the Right Side of Change
February 26, 2024 - For replacing spaces, the list comprehension can conditionally swap a space for another character, then ‘join’ the list back into a string. ... text = "Hello World" new_text = ''.join(['_' if char == ' ' else char for char in text]) print(new_text) ... This snippet iterates over each character in text, replacing it with an underscore if it is a space, or leaving it unchanged otherwise. This new sequence of characters is then joined back into a string without any spaces. Python’s re module is well-suited for string manipulation tasks that require pattern matching.
Top answer
1 of 2
1

It may be better to split the words, mapping the words from the start of the phrase to the full phrase, if you need the largest, instead of checking every item in the dict you just need to sort the phrases that appear by length:

from collections import defaultdict

def get_phrases(fle):
    phrase_dict = defaultdict(list)
    with open(fle) as ph:
        for line in map(str.rstrip, ph):
            k, _, phr = line.partition(" ")
            phrase_dict[k].append(line)
        return phrase_dict

from itertools import chain


def replace(fle, dct):
    with open(fle) as f:
        for line in f:
            phrases = sorted(chain.from_iterable(dct[word] for word in line.split() 
                             if word in dct) ,reverse=1, key=len)
            for phr in phrases:
                  line = line.replace(phr, phr.replace(" ", "_"))
            yield line

Output:

In [10]: cat out.txt
This is a sentence that contains multiple phrases that I need to replace with phrases with underscores, e.g. social political philosophy with political philosophy under the branch of philosophy and some computational linguistics where the cognitive linguistics and psycho cognitive linguistics appears with linguistics
In [11]: cat phrases.txt
cognitive linguistics
psycho cognitive linguistics
socio political philosophy
political philosophy
computational linguistics
linguistics
philosophy
social political philosophy
In [12]: list(replace("out.txt",get_phrases("phrases.txt")))
Out[12]: ['This is a sentence that contains multiple phrases that I need to replace with phrases with underscores, e.g. social_political_philosophy with political_philosophy under the branch of philosophy and some computational_linguistics where the cognitive_linguistics and psycho_cognitive_linguistics appears with linguistics']

A few other versions:

def repl(x):
    if x:
        return x.group().replace(" ", "_")
    return x


def replace_re(fle, dct):
    with open(fle) as f:
        for line in f:
            spl = set(line.split())
            phrases = chain.from_iterable(dct[word] for word in spl if word in dct)
            line = re.sub("|".join(phrases), repl, line)
            yield line


def replace_re2(fle, dct):
    cached = {}
    with open(fle) as f:
        for line in f:
            phrases = tuple(chain.from_iterable(dct[word] for word in set(line.split()) if word in dct))
            if phrases not in cached:
                r = re.compile("|".join(phrases))
                cached[phrases] = r
                line = r.sub(repl, line)
            else:
                line = cached[phrases].sub(repl, line)
            yield line
2 of 2
1

I would make a regex of your Dictionary to match the data.
Then on the replacement side, use a callback to replace spaces with _.

I estimate it would take less than 3 hours to do the whole thing.

Fortunately there is a Ternary Tool (Dictionary) regex generator.

To generate the regex and for what is shown below, you'll need the Trial
version of RegexFormat 7

Some links:
Screenshot of tool
TernaryTool(Dictionary) - Text version Dictionary samples
A 175,000 word Dictionary Regex

You basically generate your own Dictionary
by dropping in the strings you want to find, then press the Generate button.

Then all you have to do is read in 5 MB chunks and do a find/replace using the
regex, then append it to the new file.. rinse repeat.
Pretty simple really.

Based on your sample (above) this is an estimate of the time it would take
to complete 10 Billion lines.

This analysis is based on using a benchmark that was run on your sample input using the generated regex (below).

19 lines  (@ 3600 chars)

Completed iterations:   50  /  50     ( x 1000 )
Matches found per iteration:   5
Elapsed Time:    4.03 s,   4034.28 ms,   4034278 µs

////////////////////////////
3606 chars
x 50,000
------------
180,300,000  (chars)

or 

20 lines
x 50,000
------------
1,000,000  (lines)
=========================
10,000,000,000 lines
/
1,000,000  (lines) per 4 seconds
-----------------------------------------
40,000 seconds
/
3600 secs per hour
-------------------------
11 hours
////////////////////////////

However, if you read in and process 5 megabyte chunks
(as a single string) it will reduce the engine overhead
and have the time down to 1-3 hours.

This is the generated regex for your sample Dictionary (compressed):

\b(?:c(?:linical |o(?:gnitive |mp(?:arative |ound[ ]morphology|utational[ ]linguistics)|rrelation|sm(?:etic[ ]dentistry|o(?:graphy|logy)))|r(?:anio(?:logy|metry)|iminology|y(?:o(?:biology|genics|nics)|ptanalysis|stallography))|urvilinear[ ]correlation|y(?:bernetics|to(?:genetics|logy)))|de(?:ixis|mography|nt(?:al |istry))|p(?:hilosophy|olitical[ ]philosophy))\b

(Note that the space separation are generated as [ ] per space.
If you want to change it to a quantified class, just run a
find (?:\[ \])+ and replace with whatever you want.
For example \s+ or [ ]+
)


Here it is Formatted:

 \b 
 (?:
      c
      (?:
           linical [ ] 
           (?: anatomy | psychology )
        |  o
           (?:
                gnitive [ ] 
                (?: neuroscience | psychology | science )
             |  mp
                (?:
                     arative [ ] 
                     (?: anatomy | psychology )
                  |  ound [ ] morphology
                  |  utational [ ] linguistics
                )
             |  rrelation
             |  sm
                (?:
                     etic [ ] dentistry
                  |  o
                     (?: graphy | logy )
                )
           )
        |  r
           (?:
                anio
                (?: logy | metry )
             |  iminology
             |  y
                (?:
                     o
                     (?: biology | genics | nics )
                  |  ptanalysis
                  |  stallography
                )
           )
        |  urvilinear [ ] correlation
        |  y
           (?:
                bernetics
             |  to
                (?: genetics | logy )
           )
      )
   |  de
      (?:
           ixis
        |  mography
        |  nt
           (?:
                al [ ] 
                (?: anatomy | surgery )
             |  istry
           )
      )
   |  p
      (?: hilosophy | olitical [ ] philosophy )
 )
 \b 

Adding 10,000 phrases is very easy and the regex is no bigger than
the amount of bytes in the phrases plus a bit of overhead to interlace
the regex.

A final note. You can reduce the time even further by only generating the
regex on phrases.. that is only words separated by horizontal whitespace.

And, be sure to pre-compile the regex. Only have to do this once.

🌐
Finxter
blog.finxter.com › how-to-replace-whitespaces-with-underscores
How to Replace Whitespaces with Underscores – Be on the Right Side of Change
The following code instantiates a for loop, which loops through and analyzes each character of orig_quote. Each time a whitespace character is encountered, it is replaced with the underscore character and appended to new_quote.
🌐
ItSolutionstuff
itsolutionstuff.com › post › how-to-replace-whitespace-with-underscore-in-pythonexample.html
How to Replace Whitespace with Underscore in Python? - ItSolutionstuff.com
October 30, 2023 - We will use how to replace whitespace with underscore in python string. In this example, I will add myString variable with hello string. Then we will use replace() function to replace spaces with underscore in python string.
🌐
ItSolutionstuff
itsolutionstuff.com › post › how-to-replace-underscore-with-space-in-pythonexample.html
How to Replace Underscore with Space in Python? - ItSolutionstuff.com
October 30, 2023 - # Declare String Variable myString = "Hello_This_is_ItSolutionStuff.com_This_is_awesome." # Python string replace underscore with space myString = myString.replace("_", " ") print(myString)
🌐
JetBrains
youtrack.jetbrains.com › issue › PY-9786 › Automatically-replace-spaces-with-underscores-when-naming-functions-methods
Automatically replace spaces with underscores when ...
{{ (>_<) }} This version of your browser is not supported. Try upgrading to the latest stable version. Something went seriously wrong
🌐
GitHub
gist.github.com › kranthilakum › 7536042
Python script to replace underscores with spaces · GitHub
Save kranthilakum/7536042 to your computer and use it in GitHub Desktop. Download ZIP · Python script to replace underscores with spaces · Raw · rename_files.py · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below.
🌐
Tutorial Reference
tutorialreference.com › python › examples › faq › python-how-to-replace-spaces-with-underscores
How to Replace Spaces with Underscores in Python Strings | Tutorial Reference
my_str.split(): Splits the string into a list of words, using any whitespace as the delimiter (multiple spaces are treated as one). '_'.join(...): Joins the words back together, using an underscore as the separator.
🌐
Codemia
codemia.io › home › knowledge hub › how to replace whitespaces with underscore?
How to replace whitespaces with underscore? | Codemia
September 23, 2025 - Assuming text.replace(" ", "_") handles all whitespace characters, when it only replaces literal spaces. Forgetting to trim leading and trailing whitespace, resulting in unwanted underscores at the edges. Not collapsing repeated whitespace, which can generate hard-to-read identifiers like ...