Splitting Strings

Today, I woke up at 4:00 AM and completed most of my algorithm subject’s topics. I also did some of my preparations at TCC up to 11 AM as I was very much involved in Knapsack topic and wanted to complete it today.

Then, I started working on my project and the first problem that I faced was splitting a string like “(1,2,3,4,5), (4,2,6,2,5), (5,2,5,62,3)” into a list of tuples containing integers like [(1,2,3,4,5), (4,2,6,2,5), (5,2,5,62,3)]. So, I started looking for split function, but it didn’t help as it could only split with one delimiter. Then, I found “re” library which could split with a regex defined as a delimiter. So, I made the regex that served my purpose. Here is it: \((.*?)\). It split the line into a list of strings which were points.

So, the next thing was to convert each string into a tuple and each number into an integer type. So, I searched a lot over the internet, used my mind and after a lot of trials, I got this answer:

line = "(1,2,4,6),(2,5,2,5),(6,3,6,2)"

#extract each point
point_in_string = re.findall("\((.*?)\)", line)

result = []
#makes every point a tuple in a list and convert string into int
for x in point_in_string:
temp = tuple(int(y) for y in x.split(","),)
result.append(temp)

But, I have got a lot of other problems too. For including this type of line, I have to change the logic of the code and I will do it tomorrow.

Advertisements