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
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, ","));
Haskell: how to print each element of list separated with comma
You can use intercalate
. It'll insert the comma between each element of the list and concatenate the resulting list of strings to turn it into a single string.
import Data.List
toCommaSeparatedString :: [String] -> String
toCommaSeparatedString = intercalate ","
ghci> toCommaSeparatedString ["1","2","3"]
"1,2,3"
print list and separate values by a comma comma and end with a dot
I would approach this by maintaining some additional state which keeps track of whether or not it is the first open locker which needs to be reported. And then, just print period outside the loop, only once.
printf("Open lockers: ");
int first = 1;
for (int i=0; i < sizeof(lockers); i++) {
if (lockers[i] == true) {
if (first == 0) {
printf(", ");
}
else {
first = 0;
}
printf("%d", i + 1);
}
}
printf(".");
Demo
Note: In the demo I replaced your bool
lockers array with an int
array. But the rest of the logic remains the same.
Related Topics
How to Set Multiple Conditions for a Loop
How to Print Bytes as Hexadecimal
Difference Between Function Template and Template Function
Combining Multiple for Loops into Single Iterator
Convert from an Infix Expression to Postfix (C++) Using Stacks
How to Peek At the Next Element in a Range-For Loop
Checking If All Elements of a Vector Are Equal in C++
While Writting Unittests for a Function, Should I Mock the Internal Function Calls Made
Carry Over Data Without Using for Loop
How to Properly Add Include Directories With Cmake
Undefined Reference to Static Class Member
Difference Between Function Overloading and Template Function Which Is More Appropriate
Remove Max Value from Simply-Connected List
How to Take Input String Till End of Line in C++ Without the Use of Getline
Finding Version of Microsoft C++ Compiler from Command-Line (For Makefiles)
How to Read Unknown Number of Inputs
C++: Modifying Array Via Function
Conditions For Automatic Generation of Default/Copy/Move Ctor and Copy/Move Assignment Operator