Im trying to reverse a string based on the block size given
for example
"the price of food is 12 dollars"
and im given a block size of 4
i want the end result to be:
food of price the dollars 12 is
im not sure how to input this into python any help would be appreciated i need this to work for any block size
To reverse a list in Python, you can use negative slicing: As you want to slice the whole list, you can omit the start and stop values altogether. To reverse the slicing, specify a negative step value. As you want to include each value in the reversed list, the step size should be -1.
Method 4: Reverse string in Python using an extended slice Extended slice offers to put a “step” field as [start, stop, step], and giving no field as start and stop indicates default to 0 and string length respectively, and “-1” denotes starting from the end and stop at the start, hence reversing a string.
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 split a list into evenly sized chunks in Python?
Using itertools
grouper 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'
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