Rearrange numbers in string
sample input : I am 5years 11 months 24days and 4 min 1second
sample out : I am 1years 4 months 5days and 11 min 24second
def sortNumbers(text):
# replace all non-digit characters by space, split result
numbers = ''.join(t if t.isdigit() else ' ' for t in text).split()
# order descending by integer value
numbers.sort(key=lambda x:-int(x))
# replace all found numbers - do not mess with the original string with
# respect to splitting, spaces or anything else - multiple spaces
# might get reduced to 1 space if you "split()" it.
for n in numbers:
text = text.replace(n, "{}")
return text.format(*numbers)
Comments
Leave a comment