Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomizing the upper and lowercase of a string

Is there a more efficient / smarter way of randomizing the uppercasing of letters in a string ? Like this:

input_string = "this is my input string"
for i in range(10):
    output_string = ""
    for letter in input_string.lower():
        if (random.randint(0,100))%2 == 0:
            output_string += letter
        else:
            output_string += letter.upper()
    print(output_string)

Output:

thiS iS MY iNPUt strInG
tHiS IS My iNPut STRInG
THiS IS mY Input sTRINg
This IS my INput STRING
ThIS is my INpUt strIng
tHIs is My INpuT STRInG
tHIs IS MY inPUt striNg
THis is my inPUT sTRiNg
thiS IS mY iNPUT strIng
THiS is MY inpUT sTRing
like image 912
François M. Avatar asked Dec 23 '22 15:12

François M.


1 Answers

You could use random.choice(), picking from str.upper and str.lower:

>>> from random import choice

>>> s = "this is my input string"
>>> lst = [str.upper, str.lower]

>>> ''.join(choice(lst)(c) for c in s)
'thiS IS MY iNpuT strIng'

>>> [''.join(choice(lst)(c) for c in s) for i in range(3)]
['thiS IS my INput stRInG', 'tHiS is MY iNPuT sTRinG', 'thiS IS my InpUT sTRiNg']
like image 143
Chris_Rands Avatar answered Jan 09 '23 15:01

Chris_Rands



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!