1
$\begingroup$

Is this a valid way to convert a string int tuple to a string float tuple, or is there a better way?

test = str((1, 1, 0))

# get chars between ()
test = test[test.find("(")+1:test.find(")")]

# if not a float already
if "." not in test:

    str_out = "("

    # add .0 to numbers
    for char in test:
        if char.isdigit():
            str_out += char + ".0"           
        else:
            str_out += char

    str_out += ")"

print(str_out)
$\endgroup$
  • 3
    $\begingroup$ This is possibly better asked on stackoverflow. If this is in relation to previous question, its not so much a matter of (needlessly) converting ints to floats its converting a flat list (1, 2, 3, 4) into a nested list ((1, 2), (3, 4)) 2x2 for brevity sake Btw above will fail with numbers > 9 $\endgroup$ – batFINGER Feb 15 at 3:41
  • 1
    $\begingroup$ Just to clarify, Python questions are okay here if they directly relate to Blender (for example in Blender Python scripting, or Python in the Blender Game Engine). General Python questions belong over at Stack Overflow. BTW, welcome to Blender Stack Exchange! $\endgroup$ – Mentalist Feb 15 at 13:06
4
$\begingroup$

Don't think you need to do that

Firstly this will convert simple tuples of ints and floats from string

>>> x = str((1, 20, 2.0))
>>> 
>>> y = tuple(float(s) for s in x.strip("()").split(","))
>>> print(y)
(1.0, 20.0, 2.0)

However if this is in relation to previous question, its not so much a matter of (needlessly) converting ints to floats its converting a flat list (1, 2, 3, 4) into a nested list ((1, 2), (3, 4)) 2x2 for brevity sake

Even if it is a flat list of floats it will throw the error because it wants the members of constraint_matrix to be sequences not a float or int.

So without bothering to convert to floats, and having converted string to list (or tuple)

>>> x = (1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> tuple(zip(*(x[i::3] for i in range(3))))
((1, 2, 3), (4, 5, 6), (7, 8, 9))

For other methods.

https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks

This is possibly better asked on stackoverflow. Consider using re or argument parsing libraries.

Btw code in question will fail with numbers > 9

$\endgroup$
  • $\begingroup$ I still need to extract that information (x) from a string though, so I could get the tuple from: from ast import literal_eval and extract then reform it? seems to be working :) $\endgroup$ – Way2Close Feb 15 at 9:02
  • $\begingroup$ Working example at blender.stackexchange.com/questions/131739/…... sorry for creating two posts when one would have done. $\endgroup$ – Way2Close Feb 16 at 8:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.