Are there any ways to scramble strings in python?

Geparada picture Geparada · May 31, 2011 · Viewed 36.7k times · Source

I'm writing a program and I need to scramble the letters of strings from a list in python. For instance I have a list of strings like:

l = ['foo', 'biology', 'sequence']

And I want something like this:

l = ['ofo', 'lbyoogil', 'qceeenus']

What is the best way to do it?

Thanks for your help!

Answer

Tim McNamara picture Tim McNamara · May 31, 2011

Python has batteries included..

>>> from random import shuffle

>>> def shuffle_word(word):
...    word = list(word)
...    shuffle(word)
...    return ''.join(word)

A list comprehension is an easy way to create a new list:

>>> L = ['foo', 'biology', 'sequence']
>>> [shuffle_word(word) for word in L]
['ofo', 'lbyooil', 'qceaenes']