-1

I'm making a text converter, and I'd like to select random characters in a string that already exists.

When I research it, all that comes up is someone that wants to generate random letters in the alphabet or someone that wants to generate a random string. That's not what I'm looking for.

new_string = ""
index = 0

for letter in input_text:
    if letter not in "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM":
        new_string = new_string + (letter)
        continue
    index += 1
    if index % 2 == 0:
        new_string = new_string + (letter.upper())
    else:
        new_string = new_string + (letter.lower())

My existing text converter capitalizes every other letter, but I'd like to have it randomly capitalize the letters. Is this possible?

j6m8
  • 2,261
  • 2
  • 26
  • 34
ali.c
  • 9
  • 2
  • 1
    Have you checked the `random` module? – yatu Jul 02 '19 at 18:39
  • Instead of checking whether the index is even or odd, you could check if a [random integer](https://docs.python.org/3/library/random.html#random.randint) is 0 or 1. – Stephen B Jul 02 '19 at 18:41
  • You should consider editing the question to fix the indentation and make the title reflect what you're actually asking. It doesn't seem like you're asking how to generate random characters. – Mark Jul 02 '19 at 18:43
  • I've edited the question for formatting. – j6m8 Jul 02 '19 at 18:49

1 Answers1

1

You may want to look at the random.choice and random.choices functions in the random library (built-in), which allows you to randomly select an item from a list:

>>> import random
>>> a = random.choice("ABCDabcd")
'C'
>>> my_text = "".join(random.choices("ABCDabcd", k=10))
'baDdbAdDDb'

In order to randomly capitalize, you can choice from a list of the lower- and upper-case version of a letter:

import random

new_string = ""
for letter in input_text:
    if letter not in "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM":
        new_string = new_string + (letter)
    else:
        new_string += random.choice([letter.upper(), letter.lower()])

(Note that random.choices returns a list, not a str, so we need to join() the elements together.)


Finally, you may also want to use the isalpha function:

>>> "A".isalpha()
True
>>> "a".isalpha()
True
>>> "7".isalpha()
False

(Relevant question)


But upper() and lower() functions have no effect on non-alpha characters. So you can completely remove this check from your code:

new_string = ""
for letter in input_text:
    new_string += random.choice([letter.upper(), letter.lower()])
j6m8
  • 2,261
  • 2
  • 26
  • 34