Python:在随机点的其他字符之间插入字符

时间:2011-09-29 09:19:05

标签: python

例如:

str = 'Hello world. Hello world.'

变成:

list = ['!','-','=','~','|']
str = 'He!l-lo wor~ld|.- H~el=lo -w!or~ld.'

3 个答案:

答案 0 :(得分:6)

import random

lst = ['!','-','=','~','|']
string = 'Hello world. Hello world.'


print ''.join('%s%s' % (x, random.choice(lst) if random.random() > 0.5 else '') for x in string)

答案 1 :(得分:1)

这是一种倾向于明确的方法,但在性能方面可能不是最佳的。

from random import randint
string = 'Hello world. Hello world.'

for char in ['!','-','=','~','|']:
    pos = randint(0, len(string) - 1)  # pick random position to insert char
    string = "".join((string[:pos], char, string[pos:]))  # insert char at pos

print string

更新

取自my answer to a related question,它基本上来自DrTysra's answer

from random import choice
S = 'Hello world. Hello world.'
L = ['!','-','=','~','|']
print ''.join('%s%s' % (x, choice((choice(L), ""))) for x in S)

答案 2 :(得分:0)

Python 3解决方案

受DrTyrsa的启发

import random

lst = ['!','-','=','~','|']
string = 'Hello world. Hello world.'

使用f-strings:

print(''.join(f"{x}{random.choice(lst) if random.randint(0,1) else ''}" for x in string))

使用str.format()

print(''.join("{}{}".format(x, random.choice(lst) if random.randint(0,1) else '') for x in string)) 

我将random() > 0.5替换为randint(0,1),因为我觉得它更冗长,同时缩短了。