Mizuki
Mizuki

Reputation: 2233

printing out value that separated with comma

I'm start learning python. I would like to output value which is separated with a comma. I tried to pass end="," in print(). But it doesn't work. I found join function in the internet but which can only join an iterable.

#Fibonacci series
a,b = 0, 1
while b < 10:
    print(b, end=",")
    a,b = b,a+b

Output:

1,1,2,3,5,8,

How do I remove comma which is added in the last value?

Upvotes: 1

Views: 82

Answers (3)

Sociopath
Sociopath

Reputation: 13401

I think you need:

a,b = 0, 1
op = []    # to store values of b
while b < 10:
    op.append(b)
    a,b = b,a+b
print(*op, sep=",") 

Output:

1,1,2,3,5,8

Edit

* inside a print used to unwrap the iterables. eg.

l1 = [1,2,3]
print(*l1)

will give you 1 2 3 and you can decide which separator you want to use. By default it is ' ' (space). In your case you need ','

with dictionary

d = {'a': 5, 'b': 7}
print(*d)

output:

a b  # it will return the keys.

Upvotes: 1

ShivYaragatti
ShivYaragatti

Reputation: 398

if you don't want last , you have to go back one char and print space like below would work. add just following print at the end will make this happen

print("\b ") # there is space char of \b

you program look like below

a,b = 0, 1
while b < 10:
    print(b, end=",")
    a,b = b,a+b
print("\b ")

Upvotes: 0

Taher A. Ghaleb
Taher A. Ghaleb

Reputation: 5240

You can simply save the output in a string and then trim the last comma when you print the output, as follows:

a,b = 0, 1
output = ''
while b < 10:
    output += str(b) + ','
    a,b = b,a+b

print(output[:-1])

Upvotes: 1

Related Questions