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?
CodePudding user response:
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
