Python: replace unused space in Unicode

In Python, I have Unicode text. This text contains inextricable spaces that I want to convert to 'x'. Non-breaking spaces are equal chr(160). I have the following code that works fine when I run it as Django via Eclipse using Localhost. Errors and any inextricable spaces are not converted.

my_text = u"hello"
my_new_text = my_text.replace(chr(160), "x")

However, when I run it in any other way (Python command line, Django via runster instead of Eclipse), I get an error message:

'ascii' codec can't decode byte 0xa0 in position 0: ordinal not in range(128)

I assume this error makes sense because it is trying to compare Unicode (my_text) with something that is not Unicode. My questions:

  • If chr(160)not Unicode, what is it?
  • How does it work when I run it from Eclipse? Understanding this will help me determine if I need to modify other parts of my code. I tested my code from Eclipse.
  • (most important) How to solve my original problem of removing inextricable spaces? my_textthere will definitely be Unicode.
+5
source share
1 answer
  • In Python 2 chr(160), a one-byte string with only a byte of 160 or hex a0. There is no point except in the context of a particular encoding.
  • I am not familiar with Eclipse, but it can play its own coding tricks.
  • If you need a Unicode character NO-BREAK SPACE, that is, code 160 unichr(160).

eg.

>>> u"hello\u00a0world".replace(unichr(160), "X")
u'helloXworld
+11
source

All Articles