Python: How to slice a string on a specific number of characters into a list?

StackOverflow https://stackoverflow.com/questions/13182185

  •  25-07-2021
  •  | 
  •  

Domanda

I am reading a line of text data and I want to split the line into a list of values. For example the line has four numbers, each one allotted 5 spaces, so if the numbers are 18, 295, -9999, and 1780 then the original line will look like this (with ^ characters denoting the start and end of line, not included in actual input data):

^   18  295-9999 1780^

I want to split the line into a list of its actual component values:

[18, 295, -9999, 1780]

I know the number of values that the list should contain (in the example above it's 4), and I know exactly how many spaces each value takes up in the string (in the example above it's 5). I can create a loop to do this splitting, like this:

values = []
for i in range(4):
    values.append(line[i*5:5])

Is there a more efficient or more "Pythonic" way of doing this?

Thanks in advance for your help.

Nessuna soluzione corretta

Altri suggerimenti

Using slicing...

>>> [int(s[i:i+5]) for i in xrange(0, len(s), 5)]
[18, 295, -9999, 1780]

Or - if you really wanted to, some people find re a bit more readable... (just throwing this in as an alternative for reference - don't shoot me!)

>>> map(int, re.findall('.{5}', s))
[18, 295, -9999, 1780]

Here is another possible solution:

x = '   18  295-9999 1780'

def split_up(x):
    return map(int, x.replace('-', ' -').split())

Result

>>> split_up(x)
[18, 295, -9999, 1780]
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top