Search code examples
pythonstringsplit

Split string by space and strip newline char


I have a string that looks like:

d4 c3 b2 a1 02 00 04 00  00 00 00 00 00 00 00 00 
ff ff 00 00 01 00 00 00  00 00 00 00 00 00 00 00 
36 00 00 00 36 00 00 00  00 1c 23 10 f8 f1 00 1b 
17 01 10 20 08 00 45 00  00 28 df 27 40 00 80 06 
2b 87 c7 08 1a 0a 0a 05  05 0a 5c ea 5c ea c2 1f 

There are many more lines that I skipped. I want to put each of the numbers in a list. When I use .split, it returns me a list of not just numbers, but also spaces and \n's, because there are two spaces in the middle of the matrix and there are newlines at the end of each line. So I got:

['d4', 'c3', 'b2', 'a1', '02', '00', '04', '00', '', '00', …, '\nff', 'ff', '00'…]

How can I get just the numbers to be in the list, not anything else?


Solution

  • If you use .split(" "), then your program will split on every single space, and not on any other whitespace. If you use .split() instead, the program will take into account multiple spaces, newlines, tabs and all other forms of whitespace. That should get you what you're looking for.

    >>> teststr = "a   v w   ef sdv   \n   wef"
    >>> print(teststr)
    a   v w   ef sdv   
       wef
    >>> teststr.split()
    ['a', 'v', 'w', 'ef', 'sdv', 'wef']
    >>> teststr.split(" ")
    ['a', '', '', 'v', 'w', '', '', 'ef', 'sdv', '', '', '\n', '', '', 'wef']