-5

i need to split this list:

1 2 3 |4 5 6 |  7  8

and make it into this:

7 8 4 5 6 1 2 3

Till now i only used the split() function, but it only splits the "|" and i get this ['1 2 3 ', '4 5 6 ', ' 7 8']. So my question is how to split the blank spaces as well(they could be more than 1).

Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
  • But you've also reversed the ordering of the segments in the output? It would be better to do that _first_ before splitting a second time. – roganjosh Nov 29 '18 at 19:47
  • `split` defaults to splitting on blanks; where are you stuck? – Prune Nov 29 '18 at 19:49
  • Yes i need to pass through each of the obtained tokens from right to left. – unknownerror Nov 29 '18 at 19:50
  • 1
    [Split Strings with Multiple Delimiters?](https://stackoverflow.com/q/1059559/674039) – wim Nov 29 '18 at 19:50
  • Is the input that you called a list really a string? Should the output be a list of integers, or a string? – wim Nov 29 '18 at 19:53
  • 1
    A reversed list of integers can be interpreted as `8 7 6 5 4 3 2 1` whereas your expected output is different. – slider Nov 29 '18 at 19:58

4 Answers4

2

You can split the items in the list returned by the first split again in a generator expression:

s = '1 2 3 |4 5 6 | 7 8'
print(' '.join(i for t in s.split('|')[::-1] for i in t.split()))

This outputs:

7 8 4 5 6 1 2 3
blhsing
  • 91,368
  • 6
  • 71
  • 106
1

You can try this:

'1 2 3 |4 5 6 |  7  8'.replace('|', ' ').split()

The output will be:

['1', '2', '3', '4', '5', '6', '7', '8']

Ali Cirik
  • 1,475
  • 13
  • 21
0

Given what you are attempting to do, splitting on more than just "|" is unnecessary, as the following will work:

mystr = "1 2 3|4 5 6| 7 8"
newstr = "".join(mystr.split("|").reverse())

To answer how to split on spaces as well

mylist = []
for chunk in mystr.split("|"):
    mylist.extend(chunk.split())
C.Nivs
  • 12,353
  • 2
  • 19
  • 44
0

You can try this

a = "1 2 3 |4 5 6 |  7  8"
print([int(j) for i in a.split("|")[::-1] for j in i.split(" ") if len(j) != 0])

this will be output

[7, 8, 4, 5, 6, 1, 2, 3]
Sarang
  • 126
  • 7