How to fill in all the numbers in a line

I have many address style lines and I want to sort them in a rational way.

I am looking to fill in all the numbers in a line so that: "Flat 12A High Rise" becomes "Flat 00012A High Rise", there can be several numbers in a line.

So far I have received:

def pad_numbers_in_string(string, padding=5): numbers = re.findall("\d+", string) padded_string = '' for number in numbers: parts = string.partition(number) string = parts[2] padded_string += "%s%s" % (parts[0], parts[1].zfill(padding)) padded_string += string return padded_string 

Could this be improved - it looks monstrous to me!

+7
python string
source share
2 answers

How about this?

 re.sub('\d+', lambda x:x.group().zfill(padding), s) 

Example:

 >>> s = "Flat 12A High Rise 101B" >>> padding = 5 >>> re.sub('\d+', lambda x:x.group().zfill(padding), s) 'Flat 00012A High Rise 00101B' >>> 
+7
source share

Instead of changing your data to fit your sorting algorithm, change your sorting algorithm to accommodate your data.

See Sorting for People: Natural Order on Horror Coding :

 import re def sort_nicely( l ): """ Sort the given list in the way that humans expect. """ convert = lambda text: int(text) if text.isdigit() else text alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] l.sort( key=alphanum_key ) 
+9
source share

All Articles