有没有办法在python中加扰字符串?

问题描述 投票:8回答:4

我正在编写一个程序,我需要从python中的string中搜索lists的字母。例如,我有一个liststrings像:

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

我想要这样的东西:

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

最好的方法是什么?

谢谢你的帮助!

python string list scramble
4个回答
21
投票

Python包含电池..

>>> from random import shuffle

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

列表理解是创建新列表的简单方法:

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

4
投票
import random

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

2
投票

你可以使用random.shuffle:

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

从这里你可以建立一个功能来做你想要的。


0
投票

像我之前的那些,我会使用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']

也可以看看:

© www.soinside.com 2019 - 2024. All rights reserved.