Search code examples
pythonregexstringliststrip

Find max value when string contains alphabets


I have a string as ('3% Spandex,60% Polyester,7% Cotton,30% Other') and i want to extract the highest value which in this case would be 60% Polyester So I think it will work if I split the string into a list and then strip all numeric values which should enable me to find the position of the max value and find the highest value using that. But this is a lenghty process which I guess would slow me down. Is there any other way to do it?


Solution

  • The following should work:

    res=' '.join(max([i.split() for i in s.split(',')], key=lambda x:int(x[0].split('%')[0])))
    
    >>> print(res)
    '60% Polyester'