How to "convert" a dequed object to string in Python?

Stephen Paul picture Stephen Paul · Jul 25, 2013 · Viewed 7.9k times · Source

I am trying to output a rotated version of a string. I have taken a string, z="string", and created a deque out of it, y=collections.deque(z) (deque(['S','t','r','i','n','g']), and rotated it using the rotate method. How do I "convert" that deque object I rotated back to a string?

Answer

dawg picture dawg · Jul 25, 2013

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.