开发者

Python: Inserting characters between other characters at random points

开发者 https://www.devze.com 2023-04-09 00:52 出处:网络
For example: str = \'Hello w开发者_运维知识库orld. Hello world.\' Turns into: list = [\'!\',\'-\',\'=\',\'~\',\'|\']

For example:

str = 'Hello w开发者_运维知识库orld. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号