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.

2 Answers 2

9

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

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

Comments

Your Answer

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.