I have a string list which looks like this:
Loops = ['Loop 0 from point number 0 to 965',
'Loop 1 from point number 966 to 1969',
'Loop 2 from point number 1970 to 2961']
I am trying to get the range of the point numbers from the above list of strings.
For example: LoopStart1 = 0, LoopEnd1 = 965, LoopStart2 = 966, LoopEnd2 = 1969
I can imagine using for loops or string slicing to do that but how exactly / which commands should I use to specifically take the point numbers (integers) from these list of strings? Since the numbers each have different lengths.
Thanks in advance!
>Solution :
You can use regex
to do it. Then create a dictionary to store all values:
import re
Loops = ['Loop 0 from point number 0 to 965',
'Loop 1 from point number 966 to 1969',
'Loop 2 from point number 1970 to 2961']
d = {}
for index, value in enumerate(Loops):
m = re.findall(r'\d+ to \d+', value)
m = [i.split('to') for i in m]
d[f'LoopStart{index+1}'] = int(m[0][0])
d[f'LoopEnd{index+1}'] = int(m[0][-1])
print(d)
Output:
{'LoopStart1': 0, 'LoopEnd1': 965, 'LoopStart2': 966, 'LoopEnd2': 1969, 'LoopStart3': 1970, 'LoopEnd3': 2961}
Explanation:
This line gets the index and item of that loop. i.e. index = 0,1,2...
and value = 'Loop 0 from...', 'Loop 1 from ....'
for index, value in enumerate(Loops):
This line finds all the strings which start with a number, have ‘to’ in between, and end with a number.
m = re.findall(r'\d+ to \d+', value)
This line splits the m
string by to
.
m = [i.split('to') for i in m]
This line adds the loop item with starting value in a dictionary called d
d[f'LoopStart{index+1}'] = int(m[0][0])
This line adds the loop item with an ending value in a dictionary called d
d[f'LoopEnd{index+1}'] = int(m[0][-1])
Also, this f'{value}'
of creating strings is called f-strings
.