根据python中的块大小反转python中的字符串

根据python中的块大小反转python中的字符串,python,python-2.7,Python,Python 2.7,我正在尝试根据给定的块大小反转字符串 比如说 “食物的价格是12美元”我给了一个4块的大块头 我希望最终结果是: food of price the dollars 12 is 我不知道如何将这个输入到python中,如果有任何帮助,我们将不胜感激 我需要它来处理任何块大小使用: 相关:您实际上是在拆分列表,反转列表,然后旋转列表 所以这是可行的: >>> st='the price of food is 12 dollars' >>> li=st.spli

我正在尝试根据给定的块大小反转字符串

比如说

“食物的价格是12美元”
我给了一个4块的大块头

我希望最终结果是:

food of price the dollars 12 is
我不知道如何将这个输入到python中,如果有任何帮助,我们将不胜感激 我需要它来处理任何块大小

使用:


相关:

您实际上是在拆分列表,反转列表,然后旋转列表

所以这是可行的:

>>> 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
或者更直接地说:

>>> li='the price of food is 12 dollars'.split()[::-1]
>>> print ' '.join(li[3:]+li[:3])
food of price the dollars 12 is
或者,如果您希望它出现在函数中:

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)    
关键是:

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'

你说的块大小是指一次应该反转的字数吗?是的@lxop我指的是一次的字数nice我在等待这种回答我需要这段代码将其转换成函数这行吗@威玛,你只是。。UH把它变成一个函数,祝你好运that@root你不能,因为那样它会占用另一个额外的空间@wim的解决方案通过有两个
''来避免这个问题。加入
s,我现在更喜欢它。你自己试试看+1,这太好了,太棒了,你做的是先拆分成列表反向列表,然后在字符串中以块的形式添加回来..正确吗?是的--我在答案中添加了一个解释。-1这不适用于其他情况。例如,对于输入'abcdef'和块大小为2的情况,我们应该得到'baddcfe',但您的结果是'dcabafe'
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)    
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'