Search code examples
pythonpython-3.xuppercaselowercase

Randomly capitalize letters in string


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?


Solution

  • 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