How to replace unicode characters in string with something else python?

后端 未结 4 662
暗喜
暗喜 2020-11-29 02:51

I have a string that I got from reading a HTML webpage with bullets that have a symbol like \"•\" because of the bulleted list. Note that the text is an HTML source from a w

相关标签:
4条回答
  • 2020-11-29 03:17
    import re
    regex = re.compile("u'2022'",re.UNICODE)
    newstring = re.sub(regex, something, yourstring, <optional flags>)
    
    0 讨论(0)
  • 2020-11-29 03:19
    1. Decode the string to Unicode. Assuming it's UTF-8-encoded:

      str.decode("utf-8")
      
    2. Call the replace method and be sure to pass it a Unicode string as its first argument:

      str.decode("utf-8").replace(u"\u2022", "*")
      
    3. Encode back to UTF-8, if needed:

      str.decode("utf-8").replace(u"\u2022", "*").encode("utf-8")
      

    (Fortunately, Python 3 puts a stop to this mess. Step 3 should really only be performed just prior to I/O. Also, mind you that calling a string str shadows the built-in type str.)

    0 讨论(0)
  • 2020-11-29 03:31

    Encode string as unicode.

    >>> special = u"\u2022"
    >>> abc = u'ABC•def'
    >>> abc.replace(special,'X')
    u'ABCXdef'
    
    0 讨论(0)
  • 2020-11-29 03:34

    Funny the answer is hidden in among the answers.

    str.replace("•", "something") 
    

    would work if you use the right semantics.

    str.replace(u"\u2022","something") 
    

    works wonders ;) , thnx to RParadox for the hint.

    0 讨论(0)
提交回复
热议问题