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?
Python is all about objects thus the objects can be directly converted into strings using methods like str() and repr(). Str() method is used for the conversion of all built-in objects into strings. Similarly, repr() method as part of object conversion method is also used to convert an object back to a string.
Strings are objects in Python which means that there is a set of built-in functions that you can use to manipulate strings.
How to Convert a String to a List of Words. Another way to convert a string to a list is by using the split() Python method. The split() method splits a string into a list, where each list item is each word that makes up the string. Each word will be an individual list item.
As you learned earlier, deque is implemented as a doubly linked list. So, every item in a given deque holds a reference (pointer) to the next and previous item in the sequence. Doubly linked lists make appending and popping items from either end light and efficient operations.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With