Python Forum
Sorting digits in a mixed string
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sorting digits in a mixed string
#1
Hello.
In a mixed string(digits and English alphabet) sort only the digits.
Example:
"3b2c1" => "1b2c3"
"7Mkx1Intv2n5D" => "1Mkx2Intv5n7D"

I came up with:
s = "7Mkx1Intv2n5D"
arr = list(s)
sorted(arr, key=lambda val:'0123456789'.index(val) if val.isdigit() else ...)
I can't think of a working else condition.

The other idea I had, was to extract all the digits into a list, sort it and go over the string, replacing the digits with values from sorted list.
Reply
#2
(Apr-22-2020, 10:56 AM)snorri Wrote: The other idea I had, was to extract all the digits into a list, sort it and go over the string, replacing the digits with values from sorted list.
That looks like working solution, go for it. No need to struggle for oneliner (from Zen of python: Simple is better than complex. Complex is better than complicated.). Also how it would handle case if there are repeating numbers.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Mixed function Truman 3 3,152 Jan-20-2018, 10:46 PM
Last Post: Truman
  create a 20 digit string, and cast to a list then add all the digits as integers nikhilkumar 2 6,478 Jul-19-2017, 04:53 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020