import re
string = open('a.txt').read()
new_str = re.sub('[^a-zA-Z0-9\n\.]', ' ', string)
open('b.txt', 'w').write(new_str)

It will change every non alphanumeric char to white space.

Answer from NIlesh Sharma on Stack Overflow
Top answer
1 of 4
9
import re
string = open('a.txt').read()
new_str = re.sub('[^a-zA-Z0-9\n\.]', ' ', string)
open('b.txt', 'w').write(new_str)

It will change every non alphanumeric char to white space.

2 of 4
2

I'm pretty new and I doubt this is very elegant at all, but one option would be to take your string(s) after reading them in and running them through string.translate() to strip out the punctuation. Here is the Python documentation for it for version 2.7 (which i think you're using).

As far as the actual code, it might be something like this (but maybe someone better than me can confirm/improve on it):

fileString.translate(None, string.punctuation)

where "fileString" is the string that your open(fp) read in. "None" is provided in place of a translation table (which would normally be used to actually change some characters into others), and the second parameter, string.punctuation (a Python string constant containing all the punctuation symbols) is a set of characters that will be deleted from your string.

In the event that the above doesn't work, you could modify it as follows:

inChars = string.punctuation
outChars = ['']*32
tranlateTable = maketrans(inChars, outChars)
fileString.translate(tranlateTable)

There are a couple of other answers to similar questions i found via a quick search. I'll link them here, too, in case you can get more from them.

Removing Punctuation From Python List Items

Remove all special characters, punctuation and spaces from string

Strip Specific Punctuation in Python 2.x


Finally, if what I've said is completely wrong please comment and i'll remove it so that others don't try what I've said and become frustrated.

🌐
Medium
medium.com › @ryan_forrester_ › remove-special-characters-from-strings-in-python-complete-guide-53651c8163d9
Remove Special Characters from Strings in Python: Complete Guide | by ryan | Medium
January 7, 2025 - def clean_filename(filename): # Remove characters that are invalid in file names invalid_chars = '<>:"/\\|?*' for char in invalid_chars: filename = filename.replace(char, '') return filename.strip() # Example: Cleaning user-submitted file names dirty_filename = "My:Cool*File.txt" clean_name = clean_filename(dirty_filename) print(clean_name) # Output: "MyCoolFile.txt" def create_url_slug(text): # Convert to lowercase and replace spaces with hyphens slug = text.lower().strip() # Remove special characters slug = re.sub(r'[^a-z0-9\s-]', '', slug) # Replace spaces with hyphens slug = re.sub(r'\s+', '-', slug) # Remove multiple hyphens slug = re.sub(r'-+', '-', slug) return slug # Example: Creating a URL-friendly slug article_title = "10 Tips & Tricks for Python Programming!" url_slug = create_url_slug(article_title) print(url_slug) # Output: "10-tips-tricks-for-python-programming"
Discussions

Strip special characters from text file but keep new lines (Python) - Stack Overflow
I have a text file that looks like the following: Don't Can't Won't Shouldn't My aim is to remove all special characters from the text file, whilst preserving the new line for each word. Output More on stackoverflow.com
🌐 stackoverflow.com
November 23, 2017
python 3.x - Removing special characters from a text file - Stack Overflow
My input.txt is as below \n\n \n \n\n \n\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n \r\n \r\n\r\n\r\n \r\n\r\n\r\n\r\n \r\n\r\n\... More on stackoverflow.com
🌐 stackoverflow.com
How to remove special characters from text file using python
Find answers to How to remove special characters from text file using python from the expert community at Experts Exchange More on experts-exchange.com
🌐 experts-exchange.com
July 5, 2014
regex - How to remove special characters except space from a file in python? - Stack Overflow
I have a huge corpus of text (line by line) and I want to remove special characters but sustain the space and structure of the string. hello? there A-Z-R_T(,**), world, welcome to python. this **... More on stackoverflow.com
🌐 stackoverflow.com
April 12, 2017
🌐
Quora
quora.com › In-Python-how-do-I-remove-all-special-characters-and-spaces-in-a-text-file
In Python, how do I remove all special characters and spaces in a text file? - Quora
This is the python code for removing the special characters,spaces etc from the above file. The below is the new text file rough_2.txt without any special characters or spaces in it and contains the same text as file rough_1.txt
🌐
CodeSpeedy
codespeedy.com › home › how to remove all the special characters from a text file in python
Remove all the special characters from a text file in Python - CodeSpeedy
March 19, 2020 - Myfile = open("input.txt", "r") #my text is named input.txt #'r' along with file name depicts that we want to read it · It will check all characters for any special characters or whitespaces. We use the function isalnum() and remove all the ...
🌐
YouTube
youtube.com › watch
Python 3 Script to Remove Special Characters From Text File Using Regular Expression Full Project - YouTube
Visit my Online Free Media Tool Website https://freemediatools.com/Welcome Folks My name is Gautam and Welcome to Coding Shiksha a Place for All Programmers....
Published   February 26, 2021
🌐
Medium
medium.com › @blueberry92450 › three-ways-to-remove-special-characters-from-string-in-python-da1035cc93b8
Three ways to Remove Special Characters from String in Python Including Time Comparison | Medium
August 8, 2022 - Using replace built in method in python requires a customized function. def replace_symbol(filename): for symbol in ['*', '?', '%', '&', '$', '(', ')', '#', '^', '@', '!', '~', '-', '+', '=', " ", ",", "'", '"',"/", "."]: if symbol in filename: filename = filename.replace(symbol, '') return filename
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-removing-unwanted-characters-from-string
Remove Special Characters from String in Python - GeeksforGeeks
July 11, 2025 - ... Explanation: list comprehension iterate through each character in the string s and includes only those that are alphanumeric using char.isalnum(). The join() function then combines these characters into a new string. translate() method removes ...
Find elsewhere
🌐
Experts Exchange
experts-exchange.com › questions › 28469913 › How-to-remove-special-characters-from-text-file-using-python.html
Solved: How to remove special characters from text file using python | Experts Exchange
July 5, 2014 - The specific characters that i need removed are @ / \ [ ] < > * - _. The process that this might follow is, 1.open file 2.read file 3.remove special characters 4.save file with same file name but this needs to work automatically throughout the entire specified directory. the version of python im using is 2.7.3 on a windows machine.
🌐
Scaler
scaler.com › home › topics › remove special characters from string python
Remove Special Characters From String Python - Scaler Topics
January 6, 2024 - The string.isalnum() method returns True if all the characters in the string are alphabets or numbers and returns False if it finds any special character in the string. We can use this property to remove all special characters from a string in python.
🌐
Delft Stack
delftstack.com › home › howto › python › remove special characters from string python
How to Remove Special Characters From the String in Python | Delft Stack
February 2, 2024 - The resulting translation_table maps each special character to None, effectively indicating that they should be removed from the string. Step 3: Apply the Translation using the translate() Method · With the translation table in place, we apply it to the original string using the translate() method. This method applies the translation table and returns a new string with the specified character substitutions or removals. The map() function is a built-in Python function that applies a given function to each item of an iterable (e.g., a list, tuple, or string) and returns an iterator.
🌐
Yang Tavares
yangtavaresblog.wordpress.com › 2018 › 05 › 14 › a-way-to-remove-special-characters-from-a-text-file
A way to remove special characters from a text file | Yang Tavares
May 14, 2018 - text_file = open('text.txt','r') ... = literal_eval(text_file) The trick consists of using the “repr()” function which returns the completely “raw” string....
🌐
datagy
datagy.io › home › python posts › python strings › python: remove special characters from a string
Python: Remove Special Characters from a String • datagy
December 17, 2022 - Similar to using a for loop, we can also use the filter() function to use Python to remove special characters from a string. ... Since strings are iterable, we can pass in a function that removes special characters.
🌐
StudyMite
studymite.com › python › remove-special-characters-from-a-string-in-python-using-regex
Remove Special Characters from a String in Python Using Regex | StudyMite
March 2, 2023 - Learn how to remove special characters from a string in Python using Regex with various methods like using sub(), translate(),replace(),etc
🌐
Reddit
reddit.com › r/learnpython › how to delete special characters in the title of a file?
r/learnpython on Reddit: How to delete special characters in the title of a file?
June 19, 2022 -

Hi, basically in my python script i'm using to learn I'm trying to select the title of a web page and then save a txt file with the same name of the title of the webpage. The only problem is, if the title of the web page contains special characters such as : then the name of the txt is truncated just before this special character. How do I avoid this problem? I'm fine with completely deleting the special character from the name of the txt file.

I have tried this, during the selection

p.title = title_page['title'] + contents.replace(':','')

and also the same at the end, during the save of the file, but it doesn't work, it tells me contents is not defined in both situations. The problem is I cannot define it since the special character may be there but it may also NOT be there. How do I fix this?

Thanks

🌐
Medium
medium.com › @vidvatek › how-to-remove-special-characters-from-string-in-python-13b04516421a
How to Remove Special Characters from String in Python | Medium
December 15, 2023 - Special characters, such as punctuation marks, symbols, or non-alphanumeric characters, can often clutter text data and interfere with various text processing tasks like natural language processing, text classification, or data analysis. Python provides an array of tools and techniques to efficiently tackle this challenge. In this comprehensive guide, we will explore multiple methods and strategies for effectively removing special characters from strings in Python.
🌐
Linux Hint
linuxhint.com › remove-special-characters-string-python
Remove Special Characters From String Python – Linux Hint
The “string.replace()” method is utilized to replace all instances of a specified substring in a string with a new substring. A Python string can be modified by removing special characters with this method.