Finding the shortest string in a string of words in python

后端 未结 4 911
后悔当初
后悔当初 2021-01-28 02:30

I want to write a function that would return the length of the shortest string in a string of words. Sample: \"I eat apples\" would return 1 since \"I\" is the shorted string. T

4条回答
  •  旧时难觅i
    2021-01-28 02:54

    You can use min with a key function:

    # split the string by spaces and pick the min based on the lenght of splitted string
    # Example:
    
    string = "I eat apples"
    final = min(string.split(), key = lambda x: len(x))
    
    print(final)
    # >>> I
    

提交回复
热议问题