How to Print All Items in a List with a Delimiter in Python?

Estimated read time 2 min read

To print all items in a list with a delimiter in Python, you can use the join() method to concatenate the items in the list into a single string separated by the desired delimiter. Here’s an example code snippet that shows how to print all items in a list with a delimiter:

# Define a list of strings
my_list = ['apple', 'banana', 'cherry']

# Define the delimiter
delimiter = ', '

# Concatenate the items in the list with the delimiter
result = delimiter.join(my_list)

# Print the result
print(result)

In this example, the my_list variable is a list of strings that contains three items. The delimiter variable is a string that specifies the delimiter to use between the items. The join() method is called on the delimiter variable, with the list of strings passed as an argument. The join() method concatenates the items in the list into a single string separated by the delimiter, and the resulting string is stored in the result variable.

Finally, the print() function is called with the result variable as an argument to print the concatenated string with the delimiter. The output will be:

apple, banana, cherry

Note that the last item in the list does not have a delimiter after it. If you want to add a suffix after the last item, you can simply concatenate it to the end of the result variable before printing it. For example:

# Define a list of strings
my_list = ['apple', 'banana', 'cherry']

# Define the delimiter and suffix
delimiter = ', '
suffix = ' and more'

# Concatenate the items in the list with the delimiter and suffix
result = delimiter.join(my_list) + suffix

# Print the result
print(result)

In this example, the suffix variable is a string that specifies the suffix to add after the last item. The result variable is concatenated with the suffix variable before printing it. The output will be:

apple, banana, cherry and more

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply