在Python中,如何拆分字符串并保留分隔符?這是最簡單的解釋方法。我用的是:re.split('\W', 'foo/bar spam\neggs')-> ['foo', 'bar', 'spam', 'eggs']我想要的是:someMethod('\W', 'foo/bar spam\neggs')-> ['foo', '/', 'bar', ' ', 'spam', '\n', 'eggs']原因是我想把一個字符串拆分成令牌,操作它,然后再把它放在一起。
3 回答

米琪卡哇伊
TA貢獻1998條經(jīng)驗 獲得超6個贊
>>> re.split('(\W)', 'foo/bar spam\neggs')['foo', '/', 'bar', ' ', 'spam', '\n', 'eggs']

12345678_0001
TA貢獻1802條經(jīng)驗 獲得超5個贊
另一種在Python 3上運行良好的非正則表達式解決方案
# Split strings and keep separatortest_strings = ['<Hello>', 'Hi', '<Hi> <Planet>', '<', '']def split_and_keep(s, sep): if not s: return [''] # consistent with string.split() # Find replacement character that is not used in string # i.e. just use the highest available character plus one # Note: This fails if ord(max(s)) = 0x10FFFF (ValueError) p=chr(ord(max(s))+1) return s.replace(sep, sep+p).split(p)for s in test_strings: print(split_and_keep(s, '<')) # If the unicode limit is reached it will fail explicitlyunicode_max_char = chr(1114111)ridiculous_string = '<Hello>'+unicode_max_char+'<World>'print(split_and_keep(ridiculous_string, '<'))
添加回答
舉報
0/150
提交
取消