Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find String out of String with Data in Python

I need to find a String out of String from an JSON data. I do have given an Data to search for the right string.
Here is what i have done so far:

description = "Range: 1 = RED_STRAWBERRYS, 2 = WHITE_STRAWBERRYS, 3 = PINK_RASPBERRY, 4 = BLUE_BERRY"
data = "4"
data_plus_one = "5"
msg = (description[description.find(str(data))+len(description[0:4]):description.rfind(", "+data_plus_one +" =")])
print(msg)

It does work. If I search for RED_STRAWBERRYS I do have the data = 1. And I get it back. But if i look for the last element. In this case for BLUE_BERRY then I get "BLUE_BERR" back without the last Letter. Does someone now a better way than this solution?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A regex approach to generate a dictionary with numbers as the keys and fruits as the values might work here:

description = "Range: 1 = RED_STRAWBERRYS, 2 = WHITE_STRAWBERRYS, 3 = PINK_RASPBERRY, 4 = BLUE_BERRY"
d = dict(re.findall(r'(\d+) = ([^,]+)', description))
print("one:   " + d["1"])  # one:   RED_STRAWBERRYS
print("three: " + d["3"])  # three: PINK_RASPBERRY
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading