Skip to content Skip to sidebar Skip to footer

String Split With Minimum Size

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 supp

Solution 1:

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

defpad_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]

Solution 2:

>>> (['0'] * 4 + "4.5".split('.'))[-4:]['0', '0', '4', '5']
>>> (['0'] * 4 + "4.5".split('.'))[-4:]['0', '0', '4', '5']
>>> (['0'] * 4 + "2.4.5".split('.'))[-4:]['0', '2', '4', '5']
>>> (['0'] * 4 + "1.2.4.5".split('.'))[-4:]['1', '2', '4', '5']

Solution 3:

This does the trick

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

Or a more general version

defFixedLengthListFromString(input, length, delimiter='.', padChar='0'):
    vlist = input.split(delimiter)[:length]
    vlist.extend(padChar * (length - len(vlist) ) )
    return vlist

Solution 4:

If your list is a and you want to pad it out to 4 elements

a = a + [0]*(4-len(a))

Will do the padding you require.

This works because with any list l, l * x will create a new list with the element of l repeated x times so [0]*4 is just the list [0,0,0,0]. And len(a) is the current length of your list so 4-len(a) is the number of extra elements required.

Post a Comment for "String Split With Minimum Size"