When I type the following into the interpreter I get the desired output behavior:
>>> x = (7, 2, 1, 1, 6, 2, 1, 2, 1, 2, 2, 6)
>>> y = list(x)
>>> y
[7, 2, 1, 1, 6, 2, 1, 2, 1, 2, 2, 6]
Above, I simply converted a tuple to a list. However, when I run the following code I get an answer that I don’t understand.
pwm = input("enter PWM: ")
npwm = pwm.replace('),(', ', ')
y = list(npwm)
print(y)
Output:
['(', '7', ',', ' ', '2', ',', ' ', '1', ',', ' ', '1', ',', ' ', '6', ',', ' ', '2', ',', ' ', '1', ',', ' ', '2', ',', ' ', '1', ',', ' ', '2', ',', ' ', '2', ',', ' ', '6', ')']
Can anyone explain to me what is happening? Why does the above code not product the desired output of:
[7, 2, 1, 1, 6, 2, 1, 2, 1, 2, 2, 6]
EDIT: Wow, I can’t thank everyone enough for the help! I greatly appreciate everyone’s patients and willingness to help with my beginner questions. Thank you very much. Below is the solution that I got to worked:
pwm = (7, 2, 1, 1),(6, 2, 1, 2),(1, 2, 2, 6)
npwm = pwm.replace('),(',', ').strip('(').strip(')')
y = list(ast.literal_eval(npwm))
print(y)
When you call
liston a string, it generates a list in which each character is an item in the list. So for example:Since the data returned from
inputin this case is a string, callingliston it generates a list of characters.For the sake of demonstration, here’s a basic way to convert the string
'(1, 2, 3)'into the list[1, 2, 3]:Some people have suggested using
evalon the string returned byinput. Although that would do what you want, it’s a very bad habit to get into, because python will then evaluate whatever expression the (possibly malicious) user decides to enter.Also, as Sven Marnach correctly pointed out,
inputdoes what you expect in python 2.x. Fortunately that’s been corrected in 3.0, which you must be using.