I would like to do something like:
temp=a.split()
#do some stuff with this new list
b=" ".join(temp)
where a is the original string, and b is after it has been modified. The problem is that when performing such methods, the newlines are removed from the new string. So how can I do this without removing newlines?
I assume in your third line you mean
join(temp), notjoin(a).To split and yet keep the exact “splitters”, you need the re.split function (or
splitmethod of RE objects) with a capturing group:The pieces you’d get from just
re.splitare at index 0, 2, 4, … while the odd indices have the “separators” — the exact sequences of whitespace that you’ll use to re-join the list at the end (with''.join) to get the same whitespace the original string had.You can either work directly on the even-spaced items, or you can first extract them:
then alter
yas you will, e.g.:then reinsert and join up:
Note that the
\nis exactly in the position equivalent to where it was in the original, as desired.