Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string to tuple and adding to tuple

I have a config file like this.

[rects]
rect1=(2,2,10,10)
rect2=(12,8,2,10)

I need to loop through the values and convert them to tuples. I then need to make a tuple of the tuples like

((2,2,10,10), (12,8,2,10))
like image 937
giodamelio Avatar asked Oct 15 '10 20:10

giodamelio


People also ask

How do you convert a string to a tuple?

Method #1 : Using map() + int + split() + tuple() This method can be used to solve this particular task. In this, we just split each element of string and convert to list and then we convert the list to resultant tuple.

How do you add a string to a tuple in Python?

Bottom line, the easiest way to append to a tuple is to enclose the element being added with parentheses and a comma. Save this answer.

Which of the following is used to convert string into tuple?

Python's built-in function tuple() converts any sequence object to tuple. If it is a string, each character is treated as a string and inserted in tuple separated by commas.

Can we add new value to tuple?

Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called. But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.


2 Answers

Instead of using a regex or int/string functions, you could also use the ast module's literal_eval function, which only evaluates strings that are valid Python literals. This function is safe (according to the docs). http://docs.python.org/library/ast.html#ast.literal_eval

import ast
ast.literal_eval("(1,2,3,4)") # (1,2,3,4)

And, like others have said, ConfigParser works for parsing the INI file.

like image 163
li.davidm Avatar answered Sep 30 '22 09:09

li.davidm


To turn the strings into tuples of ints (which is, I assume, what you want), you can use a regex like this:

x = "(1,2,3)"
t = tuple(int(v) for v in re.findall("[0-9]+", x))

And you can use, say, configparser to parse the config file.

like image 36
David Wolever Avatar answered Sep 30 '22 10:09

David Wolever