2014-08-28 68 views
0

我想寫這將爭奪詞語的句子,並返回一個字符串,它以不同的順序回炒一句蟒蛇

from random import shuffle 
def scramble(): 
    a=len("this is a sentence") 
    for i in range(a): 
random.shuffle("this is a sentence") 
print(random.shuffle) 

不知道如果我甚至在正確的軌道代碼,但我相信該循環可能是問題

回答

0

random.shuffle工作在一個序列,而不是一個字符串。因此,首先,使用str.split來了句拆分成單詞的列表,請撥打shuffle說,然後把它變成一個字符串再次使用str.join

from random import shuffle 

def scramble(sentence): 
    split = sentence.split() # Split the string into a list of words 
    shuffle(split) # This shuffles the list in-place. 
    return ' '.join(split) # Turn the list back into a string 

print scramble("this is a sentence") 

輸出:

sentence a this is