Printing a List Separated with Commas, Without a Trailing Comma

Printing a list separated with commas, without a trailing comma

Pass sep="," as an argument to print()

You are nearly there with the print statement.

There is no need for a loop, print has a sep parameter as well as end.

>>> print(*range(5), sep=", ")
0, 1, 2, 3, 4

A little explanation

The print builtin takes any number of items as arguments to be printed. Any non-keyword arguments will be printed, separated by sep. The default value for sep is a single space.

>>> print("hello", "world")
hello world

Changing sep has the expected result.

>>> print("hello", "world", sep=" cruel ")
hello cruel world

Each argument is stringified as with str(). Passing an iterable to the print statement will stringify the iterable as one argument.

>>> print(["hello", "world"], sep=" cruel ")
['hello', 'world']

However, if you put the asterisk in front of your iterable this decomposes it into separate arguments and allows for the intended use of sep.

>>> print(*["hello", "world"], sep=" cruel ")
hello cruel world

>>> print(*range(5), sep="---")
0---1---2---3---4

Using join as an alternative

The alternative approach for joining an iterable into a string with a given separator is to use the join method of a separator string.

>>>print(" cruel ".join(["hello", "world"]))
hello cruel world

This is slightly clumsier because it requires non-string elements to be explicitly converted to strings.

>>>print(",".join([str(i) for i in range(5)]))
0,1,2,3,4

Brute force - non-pythonic

The approach you suggest is one where a loop is used to concatenate a string adding commas along the way. Of course this produces the correct result but its much harder work.

>>>iterable = range(5)
>>>result = ""
>>>for item, i in enumerate(iterable):
>>> result = result + str(item)
>>> if i > len(iterable) - 1:
>>> result = result + ","
>>>print(result)
0,1,2,3,4

I need to print without comma in last position

You can check the index before printing

n = int(input("Enter a number :-"))
for i in range(1, 11):
end = "," if i < 10 else ""
print(i*n, end = end)

How to remove last comma from print(string, end=“, ”)

You could build a list of strings in your for loop and print afterword using join:

strings = []

for ...:
# some work to generate string
strings.append(sting)

print(', '.join(strings))

alternatively, if your something has a well-defined length (i.e you can len(something)), you can select the string terminator differently in the end case:

for i, x in enumerate(something):
#some operation to generate string

if i < len(something) - 1:
print(string, end=', ')
else:
print(string)

UPDATE based on real example code:

Taking this piece of your code:

value = input("")
string = ""
for unit_value in value.split(", "):
if unit_value.split(' ', 1)[0] == "negative":
neg_value = unit_value.split(' ', 1)[1]
string = "-" + str(challenge1(neg_value.lower()))
else:
string = str(challenge1(unit_value.lower()))

print(string, end=", ")

and following the first suggestion above, I get:

value = input("")
string = ""
strings = []
for unit_value in value.split(", "):
if unit_value.split(' ', 1)[0] == "negative":
neg_value = unit_value.split(' ', 1)[1]
string = "-" + str(challenge1(neg_value.lower()))
else:
string = str(challenge1(unit_value.lower()))

strings.append(string)

print(', '.join(strings))

How can I print a list of elements separated by commas?

Use an infix_iterator:

// infix_iterator.h 
//
// Lifted from Jerry Coffin's 's prefix_ostream_iterator
#if !defined(INFIX_ITERATOR_H_)
#define INFIX_ITERATOR_H_
#include <ostream>
#include <iterator>
template <class T,
class charT=char,
class traits=std::char_traits<charT> >
class infix_ostream_iterator :
public std::iterator<std::output_iterator_tag,void,void,void,void>
{
std::basic_ostream<charT,traits> *os;
charT const* delimiter;
bool first_elem;
public:
typedef charT char_type;
typedef traits traits_type;
typedef std::basic_ostream<charT,traits> ostream_type;
infix_ostream_iterator(ostream_type& s)
: os(&s),delimiter(0), first_elem(true)
{}
infix_ostream_iterator(ostream_type& s, charT const *d)
: os(&s),delimiter(d), first_elem(true)
{}
infix_ostream_iterator<T,charT,traits>& operator=(T const &item)
{
// Here's the only real change from ostream_iterator:
// Normally, the '*os << item;' would come before the 'if'.
if (!first_elem && delimiter != 0)
*os << delimiter;
*os << item;
first_elem = false;
return *this;
}
infix_ostream_iterator<T,charT,traits> &operator*() {
return *this;
}
infix_ostream_iterator<T,charT,traits> &operator++() {
return *this;
}
infix_ostream_iterator<T,charT,traits> &operator++(int) {
return *this;
}
};
#endif

Usage would be something like:

#include "infix_iterator.h"

// ...
std::copy(keywords.begin(), keywords.end(), infix_iterator(out, ","));


Related Topics



Leave a reply



Submit