简体   繁体   English

如何在Python中找到最长的字符串?

[英]How do I find the longest string in Python?

Something like max(len(s1), len(s2)) will only return the maximum length. max(len(s1), len(s2))这样的东西只会返回最大长度。 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. max(s1,s2)似乎返回值较大的字符串,但不一定是最长的字符串。

Note: this has to be done without lists or arrays. 注意:必须在没有列表或数组的情况下完成此操作。

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接受一个key函数,使得max为每个val取最大key(val) ,但仍然返回val ,如下:

>>> max("foobar", "angstalot")
'foobar'
>>> max("foobar", "angstalot", key=len)
'angstalot'

只需要一个基于每个字符串长度的简单条件表达式:

longest = s1 if len(s1) > len(s2) else s2
def longest(a, b):
   if len(a) > len(b):
       return a
   return b

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM