how can you invoke random characters in a string closed?

I think I can roughly see what you’re going for, but correct me if I’m wrong:

You want to scramble a message by reversing the input string, and add a random symbol every 6th character.

You have already reversed the string, and are iterating over each character, but are not figuring out how to build the new string with randomized symbols.

If you want to count every 6th character, you’ll need a number to track each character in addition to the character itself. For this it is very convenient to use the enumerate function in your for loop. Then you can use math to figure out if you’re on the 6th character or not:

for index, letter in enumerate(word):
    if index % 2 == 0 and index % 3 == 0:
        # what do I put here??????????????
print(word)

From there you need to start building your new output string (you can only ever make a new string in python, never modify an existing one. Overwriting the variable may look like modifying an existing string, but internally it creates an entire new one before overwriting the existing one which is why you can’t do something like this: my_string[3] = 'G'). For this we’ll create a variable which we’ll add the characters to in order:

new_word = '' #empty string
for index, letter in enumerate(word):
    new_word = new_word + letter
    if index % 2 == 0 and index % 3 == 0:
        # what do I put here??????????????
print(new_word)

Now to get a random symbol to add every 6th character, we’ll use the random library by calling import random at the beginning of the script. The random.choice() function will choose a random element from your list of symbols which we can then add to the new_word we’re building.

new_word = '' #empty string
for index, letter in enumerate(word):
    new_word = new_word + letter
    if index % 2 == 0 and index % 3 == 0:
        random_char = random.choice(symbols)
        new_word = new_word + random_char
print(new_word)

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top