There is a string like:

CellInfo:51342693,465,6290 

you need to parse the string and output something like:

 Cell Info: First String: 51342693 Second String: 465 Third: 6290 

How to do it?

tried to use print ("First String" + s [10:19])

But the snag is that the values ​​change and may be shorter and the indexes are already working incorrectly.

 x=ser.readline(x) if(re.findall("[0-9]",x)): values=x.split(':')[1].split(',') print('First String: %x ' % values[0]) 
  • And there can only be numbers? - gil9red am

3 answers 3

 s = "CellInfo:51342693,465,6290" values = s.split(':')[1].split(',') print('First string: %s' % values[0]) print('Second string: %s' % values[1]) print('Third string: %s' % values[2]) 
  • Thank. Almost works, but gives an error: "a number is required, not str" for% x format. I tried to add: "print ('First string:% s'% int (values ​​[0]))" The error disappeared, but the output is not correct. Something like: First string: 51c65 " - Oleksandr Shulha
  • An error occurs because this parsing is for a string that is not entered into the program, but comes as an output, i.e. str. And your method parsit digits as int. - Oleksandr Shulha
  • Alexander's @OleksandrShulha method all parses as needed. Add to the question the code that works for you with an error. - strawdog 1:59 pm
  • added code. As I said, the output is read from the serial port as a string, so the error is Oleksandr Shulha
  • one
    And why do you persistently write in the %x formatted string? You were also offered to write %s - a string variable. And %x is a signed hexadecimal value. - strawdog
 l_digits = re.findall(r'[+-]?\d+(?:\.\d+)?', str) for i in range(0,len(l_digits)): print('First String: ' + i.__str__() +l_digits[i]) print('Second str: ' + i.__str__() +l_digits[i]) 

    Through the regular season:

     import re text = 'CellInfo:51342693,465,6290' match = re.search('CellInfo:(\w+),(\w+).(\w+)', text) if match: print('Cell Info:') print('First String:', match[1]) print('Second String:', match[2]) print('Third:', match[3]) # Cell Info: # First String: 51342693 # Second String: 465 # Third: 6290