Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

python unicode string in regexes

I have an unicode encoded (with BOM) source file and some string that contains unicode symbols. I want to replace all characters that not belong to a defined character set with an underscore.

# coding: utf-8 
import os
import sys
import re
t = "🙂 [°] \n € dsf $ ¬ 1 Ä 2 t34円Ú";
print re.sub(r'[^A-Za-z0-9 !#%&()*+,-./:;<=>?[\]^_{|}~"\'\\]', '_', t, flags=re.UNICODE)
output: ____ [__] _ ___ dsf _ __ 1 __ 2 t3__4__
expected: _ [_] _ _ dsf _ _ 1 _ 2 t3_4_

But each character is replaced by a number of its underscores that may be equal to the bytes in its unicode representation.

Maybe an additional problem:

In the actual problem the strings is read from a unicode file by another python module and I do not know if it handles the unicodeness correctly. So may be the string variable is marked as ascii but contains unicode sequences.

Answer*

Draft saved
Draft discarded
Cancel
4
  • Your string with complex emoji is composed of 11 characters, and 11 underscores are returned. Commented May 8, 2018 at 0:10
  • @IgnacioVazquez-Abrams hence the problem. Visually the complex emoji looks like one character (or four, on my current browser). Not an easy problem to solve. The 3rd party regex module can detect graphemes, but I'm just pointing out the problem is still complex. Commented May 8, 2018 at 13:59
  • thanks, but what if (my addition at the end) the string is defined somewhere and is not a unicode string but a normal string that was read in without proper encoding set. Ho can i treat this string (that is mor kind of a byte array) as an unicde string? Commented May 9, 2018 at 6:27
  • @vlad_tepesch .decode() the string with the correct encoding. Commented May 9, 2018 at 6:59

lang-py

AltStyle によって変換されたページ (->オリジナル) /