ngqth
ngqth

Reputation: 35

Print format in python

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.

Upvotes: 1

Views: 94

Answers (2)

Alex Hall
Alex Hall

Reputation: 36013

Using str.join:

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

Or if a already only contains strings:

' --> '.join(a)

Upvotes: 9

Pierre
Pierre

Reputation: 1099

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

Upvotes: 3

Related Questions