简体   繁体   中英

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 :

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

Inspired by DrTyrsa

import random

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

Using f-strings:

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

Using 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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