Luca
Luca

Reputation: 10996

cannot get spaces between string using join

I am using a deque and at the end I want to pop the items and add them to a string. So, I tried something like:

s = str()        
for _ in range(n):
    s += " ".join(str(q.pop()))

However, this does not put spaces between the values as I expected. To replicate:

from collections import deque
q = deque()
q.appendleft(1)
q.appendleft(2)
q.appendleft(3)

s = str()
for _in range(3):
    s += " ".join(str(q.pop()))

print(s)

This prints '123' instead of '1 2 3' as I was expecting. What am I doing wrong?

I am using python 3.5

Upvotes: 2

Views: 216

Answers (2)

bouteillebleu
bouteillebleu

Reputation: 2493

" ".join() joins the entries in an iterable together, but q.pop() only produces one item at a time.

Because str(q.pop) is still an iterable - since it's a string - join() doesn't complain at it, and just outputs each number.

If you'd had e.g. 17 in the queue, then when it was popped you'd get:

>>> " ".join(str(q.pop()))
'1 7'

Which would make it more obvious what was going wrong!

So what I'd suggest instead is:

from collections import deque
q = deque()
q.appendleft(1)
q.appendleft(2)
q.appendleft(3)

s = " ".join([str(q.pop()) for _ in range(3)])

print(s)

Where you make a list of strings based on the entries in the deque, using a list comprehension, and then join that with " ".join().

Upvotes: 2

Himanshu dua
Himanshu dua

Reputation: 2523

from collections import deque
q = deque()
q.appendleft(1)
q.appendleft(2)
q.appendleft(3)

s = str()
for _ in range(3):
    s = s + str(q.pop()) + ' '

print(s)

Upvotes: 1

Related Questions