I am trying to split a string, but keep all separators bundled together in a separate list.
s = "This is a test for \n a string"
should results in
a = ["This", "is", "a", "test", "for", "a", "string"]
b = [" ", " ", " ", " ", " \n ", " "]
Any idea on how to handle that?
re.split
is your friend:
split = re.split(r'(\s+)', s)
x = split[::2]
y = split[1::2]
>>> x
['This', 'is', 'a', 'test', 'for', 'a', 'string']
>>> y
[' ', ' ', ' ', ' ', ' \n ', ' ']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.