Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the longest string in Python?

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.

like image 597
user1689935 Avatar asked Sep 21 '12 21:09

user1689935


People also ask

How do you find the longest string?

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.

What is the largest string in Python?

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.

Can you find the length of a string in Python?

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”.


2 Answers

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'
like image 69
Claudiu Avatar answered Oct 08 '22 05:10

Claudiu


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
like image 44
martineau Avatar answered Oct 08 '22 05:10

martineau