Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Inserting characters between other characters at random points

Tags:

python

For example:

str = 'Hello world. Hello world.'

Turns into:

list = ['!','-','=','~','|']
str = 'He!l-lo wor~ld|.- H~el=lo -w!or~ld.'
like image 464
mikeyy Avatar asked Nov 01 '25 22:11

mikeyy


2 Answers

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)
like image 150
DrTyrsa Avatar answered Nov 03 '25 11:11

DrTyrsa


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)
like image 26
Shawn Chin Avatar answered Nov 03 '25 12:11

Shawn Chin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!