There are quite a few ways you could go about this. The most efficient will be using the random
module.
>>> from random import shuffle
>>> my_string = list('This is a test string.')
>>> shuffle(my_string)
>>> scrambled = ''.join(my_string)
>>> print(scrambled)
.sTtha te s rtisns gii
For this, you must create a list
from the characters of the string, because strings are immutable.
A new object has to be created if a different value has to be stored.
>>> from random import sample
>>> my_string = 'This is a test string.'
>>> scrambled = random.sample(my_string, len(my_string))
>>> scrambled = ''.join(scrambled)
>>> print(scrambled)
gr.s i tisstheit Tn sa
You don't have to create a list
for this; because, from the random.sample
documentation:
Returns a new list containing elements from the population while leaving the original population unchanged.
>>> from random import random
>>> my_string = 'This is a test string.'
>>> scrambled = sorted(my_string, key=lambda i: random())
>>> scrambled = ''.join(scrambled)
>>> print(scrambled)
ngi rts ithsT.staie s
You don't need a list
for this either. From the sorted
documentation:
Return a new sorted list from the items in iterable.
Because a string is treated as an iterable (see below) in Python, sorted
can be used on it.
An iterable is defined as
An object capable of returning its members one at a time.