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?
Asked
Active
Viewed 1.3k times
8

John Kugelman
- 349,597
- 67
- 533
- 578

Stephen Paul
- 2,762
- 2
- 21
- 25
7 Answers
7
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.

dawg
- 98,345
- 23
- 131
- 206
-
Using slice here is faster because create deque use too much time. – Windsooon Apr 15 '16 at 08:14
5
Just use str.join()
method:
>>> y.rotate(3)
>>> y
deque(['i', 'n', 'g', 's', 't', 'r'])
>>>
>>> ''.join(y)
'ingstr'

Rohit Jain
- 209,639
- 45
- 409
- 525
2
You could use the string join method:
''.join(y)
In [44]: import collections
In [45]: z = "string"
In [46]: y = collections.deque(z)
In [47]: ''.join(y)
Out[47]: 'string'

unutbu
- 842,883
- 184
- 1,785
- 1,677