Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String split with minimum size

Tags:

python

I am writing a python script that will accept a dot-delimited version number. It will split this string into individual components (using period (.) as a delimiter). My script supports up to 4 components (e.g. 1.2.3.4). However, the user may specify less or more components than 4 and my script needs to be able to handle it.

If less than 4, the list that I get back from string.split() needs to be resized to 4 and missing components initialized to the string "0". If greater than 4, just truncate the elements past the 4th component.

The truncation is easy, I would just splice the list. However, I'm not sure how to perform the resize up to 4 elements. Is there a pythonic way of doing this, or do I need to hand-write a bunch of logic to do it?

I'm using Python 3.2.

like image 579
void.pointer Avatar asked Oct 18 '25 13:10

void.pointer


2 Answers

You can generally check the length of the list and just add the missing list back to the start:

def pad_list(input_string, pad_length, pad_char='0'):
    base_version = input_string.split('.')[:pad_length]
    missing_entries = [pad_char] * pad_length - len(base_version)
    return base_version + missing_entries

Really the only addition here is to actually check the length of the partial list you're getting and then create another list with the same length as the missing section.

Alternately, you could just add the 0's ahead of time in case it's too short:

(a + '.' + '.'.join(['0'] * 4)).split('.')[:4]

The idea behind the second line here is to preemptively add zeros to your version string, which effectively eliminates your padding issue.

First, we add '.' + '.'.join(['0']*4) to the end of the string a, this adds .0.0.0.0 to the end, which means that effectively the padding is there regardless of what's in the rest of the string.

After the padding is there, you slice as you normally would: .split('.')[:4]

like image 61
Slater Victoroff Avatar answered Oct 20 '25 04:10

Slater Victoroff


This does the trick

def GetVersionList( version_string ):
    vlist = version_string.split('.')[:4]
    vlist.extend('0' * (4 - len(vlist) ) )
    return vlist

Or a more general version

def FixedLengthListFromString( input, length, delimiter='.', padChar='0' ):
    vlist = input.split(delimiter)[:length]
    vlist.extend(padChar * (length - len(vlist) ) )
    return vlist
like image 27
wallacer Avatar answered Oct 20 '25 03:10

wallacer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!