Rearrange numbers in string ?
input = I am 5 years and 11 months 20old6
output = I am 20 years and 11 months 6old5
import re
#get string from the user
inputString = input()
#get all integer from the string
numbers=[int(n) for n in re.findall(r'\d+', inputString)]
#sort all numbers
numbers.sort(reverse=True)
#Replace all numbers with the start "*"
inputString=re.sub("\d+", "*", inputString)
outputString=""
for letter in inputString:
#check if the letter in the inputed string is the star "*"
if letter=="*":
#add a number to a new string
outputString+=str(numbers.pop(0))
else:
#add a letter to a new string
outputString+=letter
#display output string
print(outputString)
Comments
Leave a comment