繁体   English   中英

Python:在任意字符之间的其他字符之间插入字符

[英]Python: Inserting characters between other characters at random points

例如:

str = 'Hello world. Hello world.'

变成:

list = ['!','-','=','~','|']
str = 'He!l-lo wor~ld|.- H~el=lo -w!or~ld.'
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)

这是一种趋于清晰的方法,但性能方面可能不是最佳方法。

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

更新资料

摘自我对一个相关问题的回答,该问题基本上源于DrTysra的回答

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

Python 3解决方案

受DrTyrsa启发

import random

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

使用f字符串:

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)) 

我用randint(0,1)替换了random() > 0.5 ,因为我发现它更加冗长,同时又更短。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM