Are there any ways to scramble strings in python?

坚强是说给别人听的谎言 提交于 2019-11-28 12:12:00

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']
import random

words = ['foo', 'biology', 'sequence']
words = [''.join(random.sample(word, len(word))) for word in words]

You can use random.shuffle:

>>> import random
>>> x = "sequence"
>>> l = list(x)
>>> random.shuffle(l)
>>> y = ''.join(l)
>>> y
'quncesee'
>>>

From this you can build up a function to do what you want.

Like those before me, I'd use random.shuffle():

>>> import random
>>> def mixup(word):
...     as_list_of_letters = list(word)
...     random.shuffle(as_list_of_letters)
...     return ''.join(as_list_of_letters)
...
>>> map(mixup, l)
['oof', 'iogylob', 'seucqene']
>>> map(mixup, l)
['foo', 'byolgio', 'ueseqcen']
>>> map(mixup, l)
['oof', 'yobgloi', 'enescque']
>>> map(mixup, l)
['oof', 'yolbgoi', 'qsecnuee']

See also:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!