1

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.

asked May 19, 2018 at 19:24

2 Answers 2

9

Using str.join:

' --> '.join(map(str, a))

Or if a already only contains strings:

' --> '.join(a)
Xantium
11.7k12 gold badges72 silver badges96 bronze badges
answered May 19, 2018 at 19:26
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.