Something like max(len(s1), len(s2))
will only return the maximum length. But if I actually want to find out which string is longer, and perhaps save it to another string, how is that done? max(s1,s2)
seems to return the string with the larger value, but not necessarily the longest.
Note: this has to be done without lists or arrays.
You find the longest string in an array. You loop over the array then you compare 2 near elements, and then return the bigger one. With your code, it will return the rabbit.
With a 64-bit Python installation, and 64 GB of memory, a Python 2 string of around 63 GB should be quite feasible. If you can upgrade your memory much beyond that, your maximum feasible strings should get proportionally longer.
To calculate the length of a string in Python, you can use the built-in len() method. It takes a string as a parameter and returns an integer as the length of that string. For example len(“educative”) will return 9 because there are 9 characters in “educative”.
max
takes a key
function which causes max
to take the max key(val)
for each val
, yet still return the val
, to wit:
>>> max("foobar", "angstalot")
'foobar'
>>> max("foobar", "angstalot", key=len)
'angstalot'
Just a simple conditional expression based on the length of each string is all that is needed:
longest = s1 if len(s1) > len(s2) else s2
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