Welcome folks today in this blog post we will be replacing blank spaces in text file with hypen 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
1 2 3 4 5 6 7 8 9 10 |
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
python app.py
Using Regular Expression
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
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!")) |