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
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
mylist = [0, 4, 8, 12]
print("The arithmetic sequence is:", ', '.join(str(i) for i in mylist))
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
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
mylist = [0, 4, 8, 12]
print("The arithmetic sequence is:", ', '.join(str(i) for i in mylist))