Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

Coverting all the list elements to string using Python?

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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'>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...