-2

I've tried:

text="Sample sentence."
random.shuffle(text)
print(''.join(text))

But this shuffles everything, possible output:

nmactnpleSSe ee

I want something like this:

Smplea ntesence.
mons
  • 1
  • 1
  • 2
    You can't shuffle a string - they are immutable. So the output shown does not correspond to the code that you have posted. – alani Oct 01 '20 at 20:44
  • `text[0] + ''.join(random.shuffle(list(text[1:-1]))) + text[-1]` as long as `len(text)` larger than 1. The idea is to maintain first and last and shuffle in between – Yossi Levi Oct 01 '20 at 20:45
  • Does this answer your question? [How to scramble the words in a sentence - Python](https://stackoverflow.com/questions/22161075/how-to-scramble-the-words-in-a-sentence-python) – Sneftel Oct 01 '20 at 20:45
  • @YossiLevi Your `shuffle` returns something other than `None`? – superb rain Oct 01 '20 at 20:53
  • correct. this one is absolutely better - `c = list(text[1:-1]);random.shuffle(c);print(text[1] + ''.join(c) + text[-1])`. thanks – Yossi Levi Oct 01 '20 at 21:07

2 Answers2

2

Just extract and shuffle the bit you want, and then reassemble it afterwards.

import random

text = "Sample sentence."

text1 = list(text[1:-1])
random.shuffle(text1)

text2 = text[0] + ''.join(text1) + text[-1]

print(text2)

Note: this answers the question as stated regarding shuffling all except the first and last character. The example shown in the question appears to be a special case, where each word gets shuffled separately. This is a possible outcome, but not a guaranteed one.

alani
  • 12,573
  • 2
  • 13
  • 23
0

See below

import random

text = 'Sample sentence.'
lst = [char for char in text[1:-1]]  
random.shuffle(lst)
lst.append(text[-1])
lst.insert(0,text[0])
print(''.join(lst))
balderman
  • 22,927
  • 7
  • 34
  • 52