compare two python strings that contain numbers
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2
--
Chapters
00:00 Compare Two Python Strings That Contain Numbers
01:03 Accepted Answer Score 14
01:39 Answer 2 Score 1
01:56 Answer 3 Score 1
02:30 Answer 4 Score 0
02:51 Thank you
--
Full question
https://stackoverflow.com/questions/6062...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #string #numbers
#avk47
ACCEPTED ANSWER
Score 14
Convert the names to tuples of integers and compare the tuples:
def splittedname(s):
    return tuple(int(x) for x in s.split('.'))
splittedname(s1) > splittedname(s2)
Update: Since your names apparently can contain other characters than digits, you'll need to check for ValueError and leave any values that can't be converted to ints unchanged:
import re
def tryint(x):
    try:
        return int(x)
    except ValueError:
        return x
def splittedname(s):
    return tuple(tryint(x) for x in re.split('([0-9]+)', s))
To sort a list of names, use splittedname as a key function to sorted:
>>> names = ['YT4.11', '4.3', 'YT4.2', '4.10', 'PT2.19', 'PT2.9']
>>> sorted(names, key=splittedname)
['4.3', '4.10', 'PT2.9', 'PT2.19', 'YT4.2', 'YT4.11']
ANSWER 2
Score 1
This is not a built-in method, but it ought to work:
>>> def lt(num1, num2):
...     for a, b in zip(num1.split('.'), num2.split('.')):
...         if int(a) < int(b):
...             return True
...         if int(a) > int(b):
...             return False
...     return False
... 
... lt('4.2', '4.11')
0: True
That can be cleaned up, but it gives you the gist.
ANSWER 3
Score 1
What you're looking for is called "natural sorting". That is opposed to "lexicographical sorting". There are several recipes out there that do this, since the exact output of what you want is implementation specific. A quick google search yields this (note* this is not my code, nor have I tested it):
import re
def tryint(s):
    try:
        return int(s)
    except:
        return s
def alphanum_key(s):
    """ Turn a string into a list of string and number chunks.
        "z23a" -> ["z", 23, "a"]
    """
    return [ tryint(c) for c in re.split('([0-9]+)', s) ]
def sort_nicely(l):
    """ Sort the given list in the way that humans expect.
    """
    l.sort(key=alphanum_key)
ANSWER 4
Score 0
use s1.split(".") to create a list of the items before and after the decimal then sort the list of lists, example:
import random
sheets = list([str(x), str(y)] for x in xrange(1, 5) for y in xrange(0,99))
print sheets
#sheets in order
random.shuffle(sheets)
print sheets
#sheets out of order
sheets.sort()
print sheets
#sheets back in order
So, you implementation might be:
#assume input sheets is a list of the worksheet names
sheets = list(x.split(".") for x in input_sheets)
sheets.sort()