Answer to Question #239044 in Python for fayaz

Question #239044

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


1
Expert's answer
2021-09-18T15:36:21-0400
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)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS