Convert string to vector

I’m new in python and sure this is an easy question.

I need to create a serie of numbers in a string to add to faces array. For example, if I have 6 faces, I want generate a string with (0,1,2,3,4,5)

I have made this code snippet to test the idea:faces = [(1,1,1),(2,2,2)]
print(faces) —> [(1,1,1),(2,2,2),(3,3,3)]

falpha = “(4,4,4)”
print(faces) —> [(1,1,1),(2,2,2),(3,3,3),(‘4’,‘4’,‘4’)]

The problem is that the values (‘4’,‘4’,‘4’) are strings, so the values cannot be used to create faces.

How can I generate the list of faces dinamically but using ints or convert falpha to ints to extend faces[]?


Hmmm… Just a bit of work on that string and you’ll get a tuple in no time.

>>> faces = [(1,1,1),(2,2,2),(3,3,3)]
>>> falpha = "(4,4,4)"
>>> faces.extend( [tuple(int(i) for i in falpha.strip("()").split(","))] )
>>> print(faces)
[(1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, 4)]

You can use float(i) instead of int(i) if you want a tuple of floats. If you expect other chars than just the parentheses around the numbers, just add them in the strip string.

In plain English:

.strip() removes whatever chars in the strip string from both ends of falpha.
.split() makes a list of strings from the resulting string, cutting the string whenever Python meets the split string.
int(i) for i in blahblah is a generator which converts each string of the list into an integer.
tuple() makes a real tuple of the result of the generator.

And your only work is to append it to the list. :wink:

EDIT: I forgot to say that it works just fine if there are spaces around the commas.

why do you add those fours as string(s)?

you could just append/extend with a tupel