Home > Back-end >  how do I extract a specific value from a string in python?
how do I extract a specific value from a string in python?

Time:12-07

I have a string with this structure:

[519.1743772241992, 519.1743772241992, 519.1743772241992, 519.1743772241992, 519.1743772241992, 519.1743772241992],12,160p30

I need to find the value after ], that here is 12. I need this value to use in a for loop. how can I do this?

CodePudding user response:

If you have same structure of data you can use regexp to extract part of strings you need to use. In described case it can be done like this:

import re


test_string = '[519.1743772241992, 519.1743772241992, 519.1743772241992, '\
                '519.1743772241992, 519.1743772241992, 519.1743772241992],'\
                '12,160p30'

pattern = r'(^\[. \]),([0-9] ),(. $)'

result = re.search(pattern, test_string)

print(result.group(1))
# [519.1743772241992, 519.1743772241992, 519.1743772241992, 519.1743772241992, 519.1743772241992, 519.1743772241992]

print(result.group(2))
# 12

print(result.group(3))
# 160p30

CodePudding user response:

If all you want is at the right end of your string, you can use rsplit instead of split

s = "[519.1743772241992, 519.1743772241992, 519.1743772241992, 519.1743772241992, 519.1743772241992, 519.1743772241992],12,160p30"
val = s.rsplit(",", 2)[1]  # val get value "12" from s

rsplit will split your string from the right starting at the separator "," a maximum of 2 times. As you want the second to last value of your string, use indexing to get the desired value.

CodePudding user response:

string = "[519.1743772241992, 519.1743772241992, 519.1743772241992, 519.1743772241992, 519.1743772241992, 519.1743772241992],1,160p30"
i = string.rfind("],")   2
value = int(string[i : string.find(",", i)])
print(value)

CodePudding user response:

yourString = ''
stringToFindLength = 2
keyCharacter = ']'
shortString = ''
for i in yourString:
   if i == keyCharacter:
      shortString = yourString[i:i stringToFindLength]

This is called string indexing, and it's a pretty big part of python, I think everything I put here would check out okay, but just in case, you should read up on string indexing:

https://www.digitalocean.com/community/tutorials/how-to-index-and-slice-strings-in-python-3

https://www.w3schools.com/python/ref_string_index.asp

there's also the index() function

yourString = ''
searchString = '12'
shortString = yourString.index(searchString)

      
  • Related