我正在尝试编写一个代码,该代码会对句子中的单词进行加扰并返回不同顺序的字符串
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 :(得分: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