Write a program in Python to find the maximum length of a string in a given Series

PythonPandasServer Side ProgrammingProgramming

Input

Assume, we have a Series like this, [“one”, “two”, “eleven”, “pomegranates”, “three”] and the maximum length of the string is “Pomegranates”

Solution

To solve this, we will follow the below approaches.

  • Define a Series

  • Set the initial value of a maxlen is 0

  • Set the “maxstr” value is initially empty string.

  • Create a for loop and access all the values in the Series one by one and create an if condition to compare the value based on the length as follows −

for i in res:
   if(len(i)>maxlen):
      maxlen = len(i)
      maxstr = i
  • Finally, print the value stored in the “maxstr” variable.

Example

Let us see the following implementation to get a better understanding.

import pandas as pd
res = pd.Series(["one","two","eleven","pomegranates","three"])
maxlen = len(res[0])
maxstr = ""
for i in res:
   if(len(i)>maxlen):
      maxlen = len(i)
      maxstr = i
print(maxstr)

Output

pomegranates
raja
Published on 10-Feb-2021 13:30:14
Advertisements