Are there any ways to scramble strings in python?

2019-01-19 15:28发布

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!

4条回答
可以哭但决不认输i
2楼-- · 2019-01-19 15:44
import random

words = ['foo', 'biology', 'sequence']
words = [''.join(random.sample(word, len(word))) for word in words]
查看更多
一夜七次
3楼-- · 2019-01-19 15:50

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:

查看更多
可以哭但决不认输i
4楼-- · 2019-01-19 15:59

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']
查看更多
We Are One
5楼-- · 2019-01-19 16:00

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.

查看更多
登录 后发表回答