close

How to remove special characters except space from a file in python?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to remove special characters except space from a file in python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to remove special characters except space from a file in python?

  1. How to remove special characters except space from a file in python?

    I think nfn neil answer is great…but i would just add a simple regex to remove all no words character,however it will consider underscore as part of the word

  2. remove special characters except space from a file in python

    I think nfn neil answer is great…but i would just add a simple regex to remove all no words character,however it will consider underscore as part of the word

Method 1

You can use this pattern, too, with regex:

import re
a = '''hello? there A-Z-R_T(,**), world, welcome to python.
this **should? the next line#followed- [email protected] an#other %million^ %%like $this.'''

for k in a.split("\n"):
    print(re.sub(r"[^a-zA-Z0-9]+", ' ', k))
    # Or:
    # final = " ".join(re.findall(r"[a-zA-Z0-9]+", k))
    # print(final)

Output:

hello there A Z R T world welcome to python 
this should the next line followed by an other million like this 

Edit:

Otherwise, you can store the final lines into a list:

final = [re.sub(r"[^a-zA-Z0-9]+", ' ', k) for k in a.split("\n")]
print(final)

Output:

['hello there A Z R T world welcome to python ', 'this should the next line followed by an other million like this ']

Method 2

I think nfn neil answer is great…but i would just add a simple regex to remove all no words character,however it will consider underscore as part of the word

print  re.sub(r'\W+', ' ', string)
>>> hello there A Z R_T world welcome to python

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read