代码之家  ›  专栏  ›  技术社区  ›  d-cubed Tyler Rinker

Python中非打印ascii字符的分行方法

  •  1
  • d-cubed Tyler Rinker  · 技术社区  · 16 年前

    在Python中,如何在非打印ascii字符(例如长减号hex 0x97、八进制227)处拆分一行? 我不需要这个角色本身。之后的信息将保存为变量。

    3 回复  |  直到 16 年前
        1
  •  5
  •   Community Mohan Dere    9 年前

    你可以用 re.split .

    >>> import re
    >>> re.split('\W+', 'Words, words, words.')
    ['Words', 'words', 'words', '']
    

    另请参见: stripping-non-printable-characters-from-a-string-in-python


    示例(带长减号):

    >>> # \xe2\x80\x93 represents a long dash (or long minus)
    >>> s = 'hello – world'
    >>> s
    'hello \xe2\x80\x93 world'
    >>> import re
    >>> re.split("\xe2\x80\x93", s)
    ['hello ', ' world']
    

    或者,与unicode相同:

    >>> # \u2013 represents a long dash, long minus or so called en-dash
    >>> s = u'hello – world'
    >>> s
    u'hello \u2013 world'
    >>> import re
    >>> re.split(u"\u2013", s)
    [u'hello ', u' world']
    
        2
  •  2
  •   tzot    16 年前
    _, _, your_result= your_input_string.partition('\x97')
    

    your_result= your_input_string.partition('\x97')[2]
    

    如果 your_input_string 不包含 '\x97' ,那么 your_result 将为空。如果 您的\u输入\u字符串 包含 '\x97' 人物, 您的\u结果 将包含第一次之后的所有内容 '\x97' 人物,包括其他 '\x97'

        3
  •  1
  •   Terence Honles    16 年前

    只需使用string/unicode split方法(他们并不真正关心您拆分的字符串(除了它是一个常量)。如果要使用正则表达式,请使用re.split)

    “\x97”

    对字符串(0-255)使用chr(0x97),对unicode使用unichr(0x97)

    'will not be split'.split(chr(0x97))
    
    'will be split here:\x97 and this is the second string'.split(chr(0x97))