Python 3 Script to Replace Blank Spaces in Text File with Underscore Using Regular Expression Full Project For Beginners

Python 3 Script to Replace Blank Spaces in Text File with Underscore Using Regular Expression Full Project For Beginners

 

Welcome folks today in this blog post we will be replacing blank spaces in text file with underscore using regular expression.All the full source code of the application is given below.

 

 

Get Started

 

 

In order to get started you need to make an app.py file and copy paste the following code

 

app.py

 

f = open("test.txt", "r")
text=f.read()
f.close()
f=open("testfile.txt", "w+")
text2=''
if ' ' in text:
    text2 = text.replace(' ' , '_')
    print(text2)
    f.write(text2)
f.close()

 

 

Now if you execute the python script by typing the below command as shown below

See also  Python 3 Script to Transfer Large Images & PDF Documents From Remote Server Using Socket Full Project For Beginners

 

python app.py

 

 

 

 

Using Regular Expression

 

 

app.py

 

import re

def urlify(s):

    # Remove all non-word characters (everything except numbers and letters)
    s = re.sub(r"[^\w\s]", '', s)

    # Replace all runs of whitespace with a single dash
    s = re.sub(r"\s+", '_', s)

    return s

# Prints: I-cant-get-no-satisfaction"
print(urlify("I can't get no satisfaction!"))

Leave a Reply