Home > front end >  Order a string by number in the string - Python
Order a string by number in the string - Python

Time:11-28

I was told to solve this but I'm not having an optimum solution

Lets say I have one string. This string is something like this

string= 'House 1 - New & Painted
         House 6
         House 2 - Used 
         House 4'

Now, i have to build a function that order this string taking account the house number, so the new string has to be something like this

string= 'House 1 - New & Painted
         House 2 - Used 
         House 4 
         House 6'

How can I do this in a function?

CodePudding user response:

You can use .splitlines() to get list of lines and use str.split to find and convert the number to integer in key function:

s = """\
House 1 - New & Painted
House 6
House 2 - Used 
House 4"""

s = "\n".join(sorted(s.splitlines(), key=lambda v: int(v.split()[1])))
print(s)

Prints:

House 1 - New & Painted
House 2 - Used 
House 4
House 6
  • Related