I have a question just purely try to improve my coding. Suggest I have a list:
a = [1, 2, 3]
I would like to print a result like below:
Path is: 1 --> 2 --> 3
My code works just fine:
text = ''
for j in range(len(a)):
text += str(a[j])
if j < len(a) - 1:
text = text + ' --> '
print('Path is:', text)
I am wondering, is there any better way to do it? Thank you.
2 Answers 2
Using str.join:
' --> '.join(map(str, a))
Or if a already only contains strings:
' --> '.join(a)
Sign up to request clarification or add additional context in comments.
Comments
You can use str.join() to create a new string with repetitions of a separator:
a = [1, 2, 3]
str_a = [str(n) for n in a]
print(" --> ".join(str_a))
answered May 19, 2018 at 19:29
Pierre
1,0991 gold badge10 silver badges14 bronze badges
Comments
lang-py