Python string inverse based on block size in python

Im trying to change the row based on the block size specified

eg

"the price of food is 12 dollars" and they are given a block size of 4

I need the final result:

 food of price the dollars 12 is 

im not sure how to introduce this in python, any help would be appreciated I need this to work for any block size

+4
source share
3 answers
 def chunks(seq, n): return [seq[i:i+n] for i in range(0, len(seq), n)] s = "the price of food is 12 dollars" ' '.join(' '.join(reversed(chunk)) for chunk in chunks(s.split(), 4)) 

Related: How do you break a list into pieces of uniform size in Python?

+6
source

Using itertools perch recipe :

 >>> from itertools import izip_longest >>> def grouper(n, iterable, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args) >>> text = "the price of food is 12 dollars" >>> ' '.join(word for g in grouper(4, text.split()) for word in reversed(g) if word) 'food of price the dollars 12 is' 
+5
source

You essentially split the list, change it, and then rotate.

So this works:

 >>> st='the price of food is 12 dollars' >>> li=st.split()[::-1] >>> n=3 >>> print ' '.join(l[n:]+l[:n]) food of price the dollars 12 is 

Or, more directly:

 >>> li='the price of food is 12 dollars'.split()[::-1] >>> print ' '.join(li[3:]+li[:3]) food of price the dollars 12 is 

Or if you want it in a function:

 def chunk(st,n): li=st.split()[::-1] # split and reverse st return ' '.join(li[n:]+li[:n]) print chunk('the price of food is 12 dollars',3) 

Key:

 st='the price of food is 12 dollars' # the string li=st.split() # split that li=li[::-1] # reverse it li=li[3:]+li[:3] # rotate it ' '.join(li) # produce the string from 'li' 
+1
source

All Articles