Home > Net >  Like str.join but with a random seperator
Like str.join but with a random seperator

Time:10-17

How would I join an iterable with a random (or otherwise chosen) string?

from itertools import cycle

options = cycle((
    ' and ',
    ' also ',
    ', ',
    ' not to mention '
))

things = ["thing A", "thing B", "thing C", "thing D also", "some other things"]

print(next(options).join(things))

Output: thing A and thing B and thing C and thing D also and some other things
Desired output: thing A and thing B also thing C, thing D not to mention some other things

What I've tried:

from itertools import cycle

options = cycle((
    ' and ',
    ' also ',
    ', ',
    ' not to mention '
))

things = ["thing A", "thing B", "thing C", "thing D also", "some other things"]

result = ''
for i, s in enumerate(things, 1):
    result  = s
    if i % len(s):
        result  = next(options)

print(result)

Output: thing A and thing B also thing C, thing D also not to mention some other things and
Desired output: thing A and thing B also thing C, thing D also not to mention some other things
This does more stuff I don't want depending on the length of things as well

CodePudding user response:

You can use functools.reduce() together with random.choice():

import functools
import random


options = (" and ", " also ", ", ", " not to mention ")


def random_join(a, b):
    return random.choice(options).join((a, b))


functools.reduce(random_join, things)

Output:

'thing A, thing B and thing C not to mention thing D also and some other things'

Note however that you have thing D also in things which I'm not sure was intentional, and sometimes produces awkward results:

'thing A and thing B, thing C, thing D also also some other things'
  • Related