I am trying to write a code that will scramble the words in a sentence and return a string that is in a different order
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)
Not sure if I am even on the right track, however I believe the loop might be the issue
random.shuffle
works on a a sequence, not a string. So first, use str.split
to split the sentence into a list of words, call shuffle
that, then turn it into a string again using 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")
Output:
sentence a this is