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

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

+5
source share
7 answers

Answer your question: since deque is a sequence , you can usually use str.join to form a string from the ordered elements of this collection. str.join works more broadly on any Python iterable to form a string of elements combined one after another.

BUT, assumption, instead of deque and rotate and join, you can also combine slices in the line itself to form a new line:

 >>> z="string" >>> rot=3 >>> z[rot:]+z[:rot] 'ingstr' 

What works in both directions:

 >>> rz=z[rot:]+z[:rot] >>> rz 'ingstr' >>> rz[-rot:]+rz[:-rot] 'string' 

Besides being easier to read (IMHO), it also turns out to be much 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)) 

Print

 True f1: 0.32 secs f2: 5.02 secs faster is 1474.49% faster. 
+5
source

Just use st. join() method:

 >>> y.rotate(3) >>> y deque(['i', 'n', 'g', 's', 't', 'r']) >>> >>> ''.join(y) 'ingstr' 
+5
source

Just concatenate the characters in a string:

 ''.join(y) 
+3
source

You can use the string concatenation method :

 ''.join(y) 

 In [44]: import collections In [45]: z = "string" In [46]: y = collections.deque(z) In [47]: ''.join(y) Out[47]: 'string' 
+2
source

Using ''.join(y) should do the trick.

+2
source

A good way is to use the join method on a string.

 ''.join(y) 
+1
source

You can use join() :

 ''.join(y) 
+1
source

Source: https://habr.com/ru/post/1493531/


All Articles