How to print a list with no leading commas with sep=", " into a string?

Question:

The title maybe a bit confusing so here is the gist of it:

I have this list:

mylist = [0, 4, 8, 12]

and I want to print only the elements after some string.

So I did this:

print("The arithmetic sequence is:", *mylist, sep=", ")

The outcome that I want is

The arithmetic sequence is: 0, 4, 8, 12

However what I got is this:

The arithmetic sequence is:, 0, 4, 8, 12

Notice the extra comma in between the 0 and the colon

I’m guessing that sep=", " is the culprit, but I don’t know how to get rid of the leading comma

Asked By: Blueyu

||

Answers:

The problem with sep= is that the string is inserted between all parameters, including between "The arithmetic sequence is:" and the first value in myList. Use a f-string and str.join instead. You’ll have to convert the values to strings as you go

>>> mylist = [0, 4, 8, 12]
>>> print(f"The arithmetic sequence is: {', '.join(str(v) for v in mylist)}")
The arithmetic sequence is: 0, 4, 8, 12
Answered By: tdelaney
mylist = [0, 4, 8, 12]
print("The arithmetic sequence is:", ', '.join(str(i) for i in mylist))
Answered By: Jethy11
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.