0

I want to randomly capitalize a letter in a string but it doesn't seem to work. I think the problem is how i'm accessing and capitalizing a letter, but i don't know any other way.
I've tried using many other answers for this question, but i could not understand their methods (i'm still pretty new) and when i tried implementing it to my code it did not work.

import random

def random_cap(word):
    for i in range(len(word)):
        rn = random.randint(0,1)
        if rn == 1:
            word[i].upper
            rn = random.randint(0,1)
    print(word)
word = input("Type word to randomly capitalize: " )
random_cap(word)
melkin
  • 1
  • `word[i].upper` does not capitalize the i-th letter in `word`. In fact it does nothing how you have it because `upper` is a method of a string, so you have to call it, and assign the result to some variable. – Anentropic Apr 25 '22 at 17:56

3 Answers3

2

Strings are immutable. word[i].upper just returns as its value the capital version of the i-th letter, but doesn't change the original string.

You need to do something like:

word = word[:i] + word[i].upper() + word[i+1:]

Alternatively, you could convert word to a list of characters:

wl = list(word)

Then randomly capitalize some of the letters:

if ...:
    wl[i] = wl[i].upper()

then put the whole thing back together as a word:

word = ''.join(wl)
Frank Yellin
  • 9,127
  • 1
  • 12
  • 22
0

You can try this:

import random

def random_cap(word):
    wordList = list(word)
    for i in range(wordList.__len__()):
        rn = random.randint(0, 1)
        if rn == 1:
            wordList[i] = wordList[i].upper()
            rn = random.randint(0, 1)
    print(''.join(wordList))
word = input("Type word to randomly capitalize: " )
random_cap(word)

Output:

Type word to randomly capitalize: I am so happy right now!
I Am sO HAPpY RIGHt nOw!

Just like Frank Yellin's code but it is based on your provided code.

Also, this could be marked as a duplicate of this question and/or this question.

WhatTheClown
  • 464
  • 1
  • 7
  • 24
0

I would try something like this:

import random

def randomize(input):
    out = str()

    for i in input:
        rn = random.randint(0, 1)
        if rn == 1:
            out += str(i.upper())
        else:
            out += str(i)

    print(out)

randomize('teststring')
FrankBlack78
  • 152
  • 11