Your ''.join() expression is filtering, removing anything non-ASCII; you could use a conditional expression instead:

return ''.join([i if ord(i) < 128 else ' ' for i in text])

This handles characters one by one and would still use one space per character replaced.

Your regular expression should just replace consecutive non-ASCII characters with a space:

re.sub(r'[^\x00-\x7F]+',' ', text)

Note the + there.

Answer from Martijn Pieters on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › transliterating-non-ascii-characters-with-python
Transliterating non-ASCII characters with Python | GeeksforGeeks
February 8, 2024 - Each key in the dictionary represents ... the replacement. For example, given the string "hello world" and a dictionary {'h': 'H', 'o': 'O'}, the output would be "Hel ... In Python, working with integers and characters is a common task, and there are various methods to convert an integer to ASCII ...
Discussions

regex - Python - Replace non-ascii character in string (») - Stack Overflow
76 UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128) 4 How can I create a string in english letters from another language word? 1 Dividing scraped text with Python and Beautiful Soup · 8 Regular expression that finds and replaces non-ascii ... More on stackoverflow.com
🌐 stackoverflow.com
python - Replace special characters with ASCII equivalent - Stack Overflow
Is there any lib that can replace special characters to ASCII equivalents, like: "Cześć" to: "Czesc" I can of course create map: {'ś':'s', 'ć': 'c'} and use some replace function. But I don't wa... More on stackoverflow.com
🌐 stackoverflow.com
Replace non-ASCII character in Python: eg, ' vs. ’ - Stack Overflow
I wan't you’ll to be reduced to you ll (not youll). This is what I'm doing: >>> clean = "you'll" >>> import string >>> clean = filter(lambda x: x in string.printable, cl... More on stackoverflow.com
🌐 stackoverflow.com
replace non ascii characters in python - Stack Overflow
Does anyone know how to replace a non ascii char in python3? I use as an example but it doesn't work the way I want to, that is to modify the new var as a string. body = "ALYSS - PYRAMID ♅" newbody = body.encode('ascii', 'ignore') ... Does this answer your question? How to make the python interpreter correctly handle non-ASCII characters ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Reddit
reddit.com › r/learnpython › how do i deal with non-ascii characters? (python 2.6)
r/learnpython on Reddit: How do I deal with non-ASCII characters? (Python 2.6)
December 22, 2013 -

My script uses strings that sometimes include foreign characters that don't exist in ASCII. (ö, ê, etc.) How do I get them to work in Python? For example, the character 'µ' gets changed to 'xb5', which makes my script fail. Is there any way to make this work?

I read somewhere that Python 3 changes the way it handles encodings, should I try to upgrade instead?

Top answer
1 of 2
3
You need to convert your text in to unicode. If you are reading those strings from files, then chances are they are in utf-8, so the following should work: my_unicode = my_string.decode('utf-8') Although it depends on the format you are trying to read. Definitely read this if you haven't already: http://docs.python.org/2/howto/unicode.html Python 2.6 can work with unicode well enough, but Python 3.X does it a bit more elegantly.
2 of 2
1
You can fake Py3 string behavior in Py2 by doing the following. Put # -*- coding: utf-8 -*- on the first or second line of every .py file and make sure your editor is set to save your .py files as UTF-8 encoded. Put from __future__ import unicode_literals before any other imports. Now every hard-coded string in your .py file is a unicode object instead of a str object. Do from io import open to replace PY2's open built-in function with Py3's open built-in function. This new open function lets you easily specify an encoding. Reading from a file opened with the new open produces a unicode string, and writing automatically encodes your unicode string. I find it a little easier to use than codecs.open. Set your terminal window to UTF-8, if possible. If you are stuck with Windows CMD.exe, your terminal will not be able to handle every Unicode character. It defaults to CP437 encoding, which can only handle 255 unique characters. Because you are interested in handling both accented Latin and also the micron character, CP437 could be fine. However, it can't handle curly quotes, euro symbol, and whatnot. Therefore, you might want to set it to CP1252. This, too, is limited to 255 unique characters, but they're more useful from an office-y standpoint. Type chcp in your CMD Command Prompt window to see the current "code page." It probably says 437. Type chcp 1252 to change it to CP1252. Now go to the Properties of your CMD Command Prompt window. Make sure the Font is a TrueType font such as Lucida Console instead of "Raster Fonts" and Save this setting. Now you're all set for CP1252 terminal IO. Python will automatically decode/encode the terminal IO to/from unicode string objects. If you find that some terminal output bombs, change your print foo Python statements to print repr(foo). Put the following code in a file called unitrial.py for experiments: #!/usr/bin/env python # -*- coding: UTF-8 -*- from __future__ import unicode_literals from io import open import sys print sys.stdin.encoding, sys.stdout.encoding melee = 'mêlée' print type(melee), melee, repr(melee) micron = '47µ' print type(micron), micron, repr(micron) doc = '“What’s up doc?”' # curly punctuation print type(doc), doc, repr(doc) with open('unitrial.py', 'rt', encoding='utf8') as f: print print f.encoding print f.read()
🌐
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 - The `str.maketrans()` function creates a translation table that maps characters to their replacements. When dealing with text in different languages, you’ll need to handle Unicode characters carefully: import unicodedata def clean_international_text(text): # Normalize Unicode characters normalized = unicodedata.normalize('NFKD', text) # Remove non-ASCII characters ascii_text = normalized.encode('ASCII', 'ignore').decode('ASCII') return ascii_text # Example with international text text = "Café München — スシ" clean_text = clean_international_text(text) print(clean_text) # Output: "Cafe Munchen "
🌐
Finxter
blog.finxter.com › home › learn python blog › 7 best ways to remove unicode characters in python
7 Best Ways to Remove Unicode Characters in Python - Be on the Right Side of Change
April 17, 2023 - In this example, we create a new string by joining only characters with ASCII code less than 128. 💡 Recommended: List Comprehension in Python — A Helpful Illustrated Guide · You can also use the replace() method to remove specific Unicode ...
Find elsewhere
🌐
DEV Community
dev.to › this-is-learning › removal-of-non-ascii-characters-using-python-8mn
Removal of Non ASCII characters using Python - DEV Community
June 10, 2021 - Below is Python script to remove those non ascii characters or junk characters. ... import re ini_string = "'technews One lone dude awaits iPad 2 at Apple\x89Ûªs SXSW store" res1 = " ".join(re.split("[^A-Za-z0-9]+", ini_string)) print(res1) if re.match("[^\t\r\n\x20-\x7E]+", ini_string): print("found") result = ini_string.encode().decode('ascii', 'replace').replace(u'\ufffd', '`') result2 = ini_string.encode().decode("utf-8").replace(u"\x89Ûª", "`").encode("utf-8") print(result2)
🌐
Python Guides
pythonguides.com › remove-non-ascii-characters-python
How Can Non-ASCII Characters Be Removed From A String In Python?
September 12, 2025 - The regex [^\x00-\x7F] matches all non-ASCII characters and removes them. This method is reliable and works when I want to strip everything outside of ASCII. Python 3.7 introduced the handy isascii() method in Python.
🌐
py4u
py4u.org › blog › python-replace-typographical-quotes-dashes-etc-with-their-ascii-counterparts
How to Replace Typographical Quotes, Dashes, and Special Characters with ASCII Counterparts in Python (While Preserving Umlauts and Non-ASCII Text)
Let’s test the function with a sample text containing typographical characters and non-ASCII text: raw_text = """ “Café Zürich” – a charming city! Its motto: ‘Stadt der Türme und Bäche’ (City of Towers and Streams). Population… approx. 420,000 (as of 2023). Don’t miss the Zürichsee—beautiful in spring! """ clean_text = replace_typographical_chars(raw_text) print(clean_text)
🌐
Rdrr.io
rdrr.io › cran › textclean › man › replace_non_ascii.html
replace_non_ascii: Replace Common Non-ASCII Characters in textclean: Text Cleaning Tools
March 5, 2026 - replace_non_ascii(x, replacement = "", remove.nonconverted = TRUE, ...) replace_non_ascii2(x, replacement = "", ...) replace_curly_quote(x, ...) Returns a text variable (character sting) with non-ASCII characters replaced.
🌐
Stack Overflow
stackoverflow.com › questions › 72720667 › replace-non-ascii-characters-in-python
replace non ascii characters in python - Stack Overflow
Does anyone know how to replace a non ascii char in python3? I use as an example but it doesn't work the way I want to, that is to modify the new var as a string. body = "ALYSS - PYRAMID ♅" newbody = body.encode('ascii', 'ignore') ... Does this answer your question? How to make the python interpreter correctly handle non-ASCII characters ...
🌐
Internetkatta
internetkatta.com › removal-of-non-ascii-characters-using-python
Removal of Non ASCII characters using Python
June 5, 2021 - Below is Python script to remove those non ascii characters or junk characters. ... import re ini_string = "'technews One lone dude awaits iPad 2 at Apple\x89Ûªs SXSW store" res1 = " ".join(re.split("[^A-Za-z0-9]+", ini_string)) print(res1) if re.match("[^\t\r\n\x20-\x7E]+", ini_string): print("found") result = ini_string.encode().decode('ascii', 'replace').replace(u'\ufffd', '`') result2 = ini_string.encode().decode("utf-8").replace(u"\x89Ûª", "`").encode("utf-8") print(result2)
Top answer
1 of 1
3

At this point w has a byte with value 160 in it, but it's encoding is 'ascii'.

You have an unicode string:

>>> w
u'\xa0 foo bar'
>>> type(w)
<type 'unicode'>

How do replace all of the \xa0 bytes with another character?

>>> x = w.replace(u'\xa0', ' ')
>>> x
u'  foo bar'

And why does BS return an 'ascii' encoded string with an invalid character in it?

As mentioned above, it is not an ascii encoded string, but an Unicode string instance.

Is there a way to convert w to a 'latin1` encoded string?

Sure:

>>> w.encode('latin1')
'\xa0 foo bar'

(Note this last string is an encoded string, not an unicode object, and its representation is not prefixed by 'u' like the previous unicode objects).

Notes (edited):

  • If you are typing strings into your source files, note that encoding of source files matters. Python will assume your source files are ASCII. The command line interpreter, on the other hand, will assume you are entering strings in your default system encoding. Of course you can override all this.
  • Avoid latin1, use UTF-8 if possible: ie. w.encode('utf8')
  • When encoding and decoding can tell Python to ignore errors, or replace characters that cannot be encoded with some marker character . I don't recommend to ignore encoding errors (at least without logging them), except for the hopefully rare cases when you know there are encoding errors or you need to encode text into a more reduced character set, requiring replacement of the code points that cannot be represented (ie if you need to encode 'España' into ASCII, you definitely should replace the 'ñ'). But for these cases there are imho better alternatives and you should look into the magical unicodedata module (see https://stackoverflow.com/a/1207479/401656).
  • There is a Python Unicode HOWTO: https://docs.python.org/2/howto/unicode.html
🌐
Stack Overflow
stackoverflow.com › questions › 34740249 › how-to-replace-non-ascii-characters
python - How to replace non-ASCII characters - Stack Overflow
I have a string in the formemail [ à ] example.com I want to make it email@example.com. I tried : print email.replace(u"\xa0", "@") print email.replace(" [ à ] ", "@") print email.replace(" à "...