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.
If you are truly comparing Strings alphabetically to arrange them in order, use compareTo() method from Comparable interface in Java. It also compare String based upon there value, and can be used to sort String alphabetically, if they are stored in List using Collections.
The Java String compareTo() method compares two strings lexicographically (alphabetical order). It returns a positive number, negative number, or zero. if s1 < s2 , it returns negative number.
We can compare strings with the help of CompareTo() method in C#. You can compare a string with another string to know if it precedes, follows, or appears in the position as the other in the sort order. An integer value is returned when the CompareTo() method is used.
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
this should work:
if len(x)==len(y): return min(x,y)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With