I have a list:
roll = [1, 2, 3]
For converting each of the element into a string, can we directly do roll = str(roll) rather that iterating over it and calling str() on each element? Is this a correct way?
I am new to Python, any hint in the right direction will do!
That wouldn't work, since that would convert the entire list into one string:
roll = [1, 2, 3]
roll = str(roll)
print(roll)
# Prints [1, 2, 3]
print(type(roll))
# Prints <class 'str'>
You can instead use a list comprehension, to convert each item in the list one by one:
roll = [1, 2, 3]
roll = [str(r) for r in roll]
print(roll)
# Prints ['1', '2', '3']
print(type(roll))
# Prints <class 'list'>
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