简体   繁体   English

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

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

For example: 例如:

str = 'Hello world. Hello world.'

Turns into: 变成:

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)

Here's an approach that leans towards clarity, but performance-wise may not be optimal. 这是一种趋于清晰的方法,但性能方面可能不是最佳方法。

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

Update 更新资料

Taken from my answer to a related question which is essentially derived from DrTysra's answer : 摘自我对一个相关问题的回答,该问题基本上源于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 Solutions Python 3解决方案

Inspired by DrTyrsa 受DrTyrsa启发

import random

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

Using f-strings: 使用f字符串:

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

Using str.format() 使用str.format()

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

I replace random() > 0.5 with randint(0,1) because I find it a bit more verbose while being shorter at the same time. 我用randint(0,1)替换了random() > 0.5 ,因为我发现它更加冗长,同时又更短。

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

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