在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条经验 获得超6个赞
>>> re.split('(\W)', 'foo/bar spam\neggs')['foo', '/', 'bar', ' ', 'spam', '\n', 'eggs']
12345678_0001
TA贡献1802条经验 获得超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
提交
取消