Randomly capitalize letters in string

  • A+

I want to randomly capitalize or lowercase each letter in a string. I'm new to working with strings in python, but I think because strings are immutable that I can't do the following:

i =0              for c in sentence:     case = random.randint(0,1)     print("case = ", case)     if case == 0:         print("here0")         sentence[i] = sentence[i].lower()     else:         print("here1")         sentence[i] = sentence[i].upper()     i += 1 print ("new sentence = ", sentence) 

And get the error: TypeError: 'str' object does not support item assignment

But then how else could I do this?


You can use str.join with a generator expression like this:

from random import choice sentence = 'Hello World' print(''.join(choice((str.upper, str.lower))(c) for c in sentence)) 

Sample output:

heLlo WORLd 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: