Separate Output With Comma In Python 3
Solution 1:
Instead of printing them immediately, put everything is a list of strings. Then join the list with commas and print resulting string.
Solution 2:
This could be a good example for learning generators. A generator looks like a normal function that uses yield
instead of return
. The difference is that when generator function is used, it behaves as an iterable object that produces a sequence of values. Try the following:
#!python3defgen():
for x inrange (1, 21):
if x % 15 == 0:
yield"fizzbuzz"elif x % 5 == 0:
yield"buzz"elif x % 3 == 0:
yield"fizz"else:
yieldstr(x)
# Now the examples of using the generator.for v in gen():
print(v)
# Another example.
lst = list(gen()) # the list() iterates through the values and builds the list objectprint(lst)
# And printing the join of the iterated elements.print(','.join(gen())) # the join iterates through the values and joins them by ','# The above ','.join(gen()) produces a single string that is printed.# The alternative approach is to use the fact the print function can accept more# printed arguments, and it is possible to set a different separator than a space.# The * in front of gen() means that the gen() will be evaluated as iterable.# Simply said, print can see it as if all the values were explicitly writen as # the print arguments.print(*gen(), sep=',')
See the doc for the print
function arguments at http://docs.python.org/3/library/functions.html#print, and *expression
call argument at http://docs.python.org/3/reference/expressions.html#calls.
Another advantage of the last print
approach is that the arguments need not to be of the string type. The reason why the gen()
definition explicitly used str(x)
instead of plain x
was because .join()
requires that all joined values have to be of the string type. The print
converts all the pased arguments to strings internally. If the gen()
used plain yield x
, and you insisted to use the join, the join
could use a generator expression to convert the arguments to strings on the fly:
','.join(str(x) for x ingen()))
It displays on my console:
c:\tmp\___python\JessicaSmith\so18500305>py a.py
1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
16
17
fizz
19
buzz
['1', '2', 'fizz', '4', 'buzz', 'fizz', '7', '8', 'fizz', 'buzz', '11', 'fizz',
'13', '14', 'fizzbuzz', '16', '17', 'fizz', '19', 'buzz']
1,2,fizz,4,buzz,fizz,7,8,fizz,buzz,11,fizz,13,14,fizzbuzz,16,17,fizz,19,buzz
1,2,fizz,4,buzz,fizz,7,8,fizz,buzz,11,fizz,13,14,fizzbuzz,16,17,fizz,19,buzz
Post a Comment for "Separate Output With Comma In Python 3"