23

Write a function that takes two strings as arguments and returns the one which is longer. If the strings have equal length, return the one that comes first alphabetically.

This is what i have so far:

    def strings(x,y):
        if len(x) > len(y):
            return x
        if len(x)==len(y):
            return 
        else:
            return y

I am wondering how i would write the code so it would choose the string that comes first alphabetically for the second if statement.

The Unfun Cat
  • 29,987
  • 31
  • 114
  • 156
user1698174
  • 469
  • 2
  • 5
  • 9
  • 11
    The incredible thing is that I can't find a duplicate for this. – The Unfun Cat Nov 12 '12 at 21:44
  • It shouldn't have been difficult to find a duplicate. The question is how to compare strings alphabetically (the bit about length is a red herring, since it is already handled), and since *that is what happens by default*, answering the question is equivalent to knowing that it happens by default - therefore, a question detailing the default behaviour is a perfectly satisfactory duplicate. That said, at varying points in Stack Overflow history, there has been an inappropriate bias against "easy" questions which has robbed us of important canonicals. – Karl Knechtel Sep 25 '22 at 22:31

3 Answers3

16

You can compare strings directly. x<y means "does x come before y alphabetically?" So you can replace your second block with:

if len(x) == len(y) and x < y:
    return x
AlwaysBTryin
  • 1,924
  • 12
  • 7
12

this should work:

if len(x)==len(y):
   return min(x,y)
gefei
  • 18,922
  • 9
  • 50
  • 67
  • 9
    `sorted(x, y)[0]` would have more clarity as to it's intent, perhaps. – Martijn Pieters Nov 12 '12 at 21:46
  • 8
    BTW, be careful when doing this for strings of mixed case. `min("B","a")` will return `"B"` as coming before `"a"`. – kreativitea Nov 12 '12 at 23:34
  • 2
    @kreativitea good point. To protect against this you could use `min(x.lower(), y.lower())` or following @Martijn Pieters' suggestion `sorted([x, y], key=str.lower)[0]` – Jonny Sep 16 '20 at 09:32
5
def f(x,y):
    return len(x) != len(y) and max([x,y],key=len) or min(x,y)
Julien Vivenot
  • 2,230
  • 13
  • 17