aldegalan
aldegalan

Reputation: 502

Take numbers of a string and operate with them

I have a string like this one:

vserver           volume                                           changelog-usage 
----------------- ------------------------------------------------ --------------- 
svm_name name_of_volume_1 11%              
svm_name2 name_of_volume_2 10%              
svm_name3 name_of_volume_3 0%              
svm_dSN_SM2M_NAS  shorter_name_4                                 15%              

And I am using this code:

matchArr = string.split("\n")
for i in matchArr:
  tmpMatchArr = i.split(" ")
  for i in range(0, len(tmpMatchArr)):
    if int(tmpMatchArr[2].replace("%", "")) < 10:
      break
    if i == 2:
      finalString += " = " + tmpMatchArr[i] + ", "
    elif i == 1:
      finalString += tmpMatchArr[i]
    else:
      finalString += tmpMatchArr[i] + "."
  
print(finalString);

The thing is, that I would like to take only those values that are greater than 10, but I am receiving this error:

IndexError: list index out of range

The desired output, is something like this:

WARNING: Usage greater than 10% at: svm_name.name_of_volume_1=11%, svm_dSN_SM2M_NAS.shorter_name_4=15%

Edit: A regex selecting the numbers, is not an option, because the name of the volume already contains some numbers...

Upvotes: 0

Views: 42

Answers (1)

Riccardo Bucco
Riccardo Bucco

Reputation: 15364

If you want to simplify things a bit you might want to consider regexes:

import re

warnings = re.findall('\n(\S+)\s+(\S+)\s+(\d+)\%', string)
print('WARNING: Usage greater than 10% at: '
      + ', '.join('{}.{}={}%'.format(*w) for w in warnings if int(w[2]) > 10))

Output:

WARNING: Usage greater than 10% at: svm_name.name_of_volume_1=11%, svm_dSN_SM2M_NAS.shorter_name_4=15%

Upvotes: 1

Related Questions