Home > Enterprise >  Slicing String based on uncertain values
Slicing String based on uncertain values

Time:01-05

I am trying to slice the below string

data = 'INFO: 2585,1,194,-105,-8,-97,14'

here I need to get values 194 & -97 for that I can do

print(data[13:16],data[25:28])
result - 194 -97

But say if the value changes from

194 to 9999

i.e some other value having extra digits

then the slicing would become incorrect kindly suggest a way to handle this

CodePudding user response:

You can split on ': ' and then on ',' and take the relevant numbers using their indices:

data = 'INFO: 2585,1,194,-105,-8,-97,14'
s = data.split(': ')[1].split(',')
first, second = s[2], s[-2]

Output:

('194', '-97')

CodePudding user response:

You can use the split() function, it splits the string by pointer, for example "194,192,196".split() will return an array of three elements: ["194","192","196"]. You can use this code:

data = 'INFO: 2585,1,194,-105,-8,-97,14'

data = data.split(": ")[1].split(",")
print(data[2], data[5])

CodePudding user response:

You can use regulat split

data = 'INFO: 2585,1,9999,-105,-8,-97,14'


data2 = data.split(",")
print(data2[2],data2[5])

Output - 9999 -97
  •  Tags:  
  • Related