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

Time:12-10

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

CodePudding user response:

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

CodePudding user response:

mylist = [0, 4, 8, 12]
print("The arithmetic sequence is:", ', '.join(str(i) for i in mylist))

CodePudding user response:

To print a list with no leading commas and using the sep=", " separator into a string, you can use the join() method on the str class. Here is an example of how this could be done in Python:

Define the list

my_list = ["apple", "banana", "cherry"]

Use the join() method to convert the list to a string

my_string = ", ".join(my_list)

Print the string

print(my_string)

In this example, the my_list variable is defined as a list of strings. The join() method is then used to convert the list to a string, using the ", " separator. The resulting string is assigned to the my_string variable, and is printed to the console.

The output of this code will be the following string:

apple, banana, cherry

As you can see, the join() method has effectively converted the list to a string, using the specified separator and without any leading commas.

  • Related