How to "convert" a dequed object to string in Python?
Answer to your question: Since a deque is a sequence, you can generally use str.join to form a string from the ordered elements of that collection. str.join
works more broadly on any Python iterable to form a string from the elements joined together one by one.
BUT, suggestion, instead of a deque and rotate and join, you can also concatenate slices on the string itself to form a new string:
>>> z="string"
>>> rot=3
>>> z[rot:]+z[:rot]
'ingstr'
Which works both ways:
>>> rz=z[rot:]+z[:rot]
>>> rz
'ingstr'
>>> rz[-rot:]+rz[:-rot]
'string'
Besides being easier to read (IMHO) It also turns out to be a whole lot faster:
from __future__ import print_function #same code for Py2 Py3
import timeit
import collections
z='string'*10
def f1(tgt,rot=3):
return tgt[rot:]+tgt[:rot]
def f2(tgt,rot=3):
y=collections.deque(tgt)
y.rotate(rot)
return ''.join(y)
print(f1(z)==f2(z)) # Make sure they produce the same result
t1=timeit.timeit("f1(z)", setup="from __main__ import f1,z")
t2=timeit.timeit("f2(z)", setup="from __main__ import f2,z")
print('f1: {:.2f} secs\nf2: {:.2f} secs\n faster is {:.2f}% faster.\n'.format(
t1,t2,(max(t1,t2)/min(t1,t2)-1)*100.0))
Prints:
True
f1: 0.32 secs
f2: 5.02 secs
faster is 1474.49% faster.
Just use str.join()
method:
>>> y.rotate(3)
>>> y
deque(['i', 'n', 'g', 's', 't', 'r'])
>>>
>>> ''.join(y)
'ingstr'
Just concatenate the characters in the string:
''.join(y)