I have a list of strings. I want to unpack it to individual variables, and while doing this I want to convert some of the strings to ints.
The brute force method might look like this
>>> my_list = ['a', '1', '2']
>>> a, b, c = my_list
>>> b = int(b)
>>> c = int(c)
>>> a,b,c
('a', 1, 2)
I'm looking for a way to do the conversions as part of the original assignment, so that I end up with something like:
>>> a, b, c = < some magic here >
>>> a,b,c
('a', 1, 2)
Anyone know what magic I'm looking for?
Fix your my_list either up stream or now before unpacking:
my_list = ['a', '1', '2']
a,b,c = (int(x) if x.isnumeric() else x for x in my_list )
print(type(a), type(b), type(c))
# <str, int int>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With