简体   繁体   中英

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

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.

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]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM