简体   繁体   中英

How to insert number every nth letter in a string in Python?

I'm writing a program to encrypt a string input. I have a random number generator, and some code that converts the random number into a letter. How would I go about inserting this letter after every say, 3rd letter? Ie String before: abcdef , String after: abcldefk.

Code for the random number generator if it helps:

Letter = random.randrange(1,26) 

print chr(Letter + ord('A'))

You can use str.join , enumerate with a start index equal to 1 and modulo:

print("".join([x if i % 3 else x + random_letter for i, x in enumerate(s,1)]))

If you just want to insert a random letter, you can use string.ascii_letters and random.choice :

from random import choice
from string import ascii_letters

s = "abcdef"
print("".join([x if i % 3 else x + choice(ascii_letters) for i, x in enumerate(s,1)])

abcQdefN

I was inspired by Padraic's answer and wanted to add a little bit more.

import random
Letter = random.randrange(1,26) 

def encrypt_string(string, n):
    return ("".join([x if i % n else chr(Letter + ord('A')) for i, x in enumerate(string)]))

Here is a string "encryption" (using it loosely) method for every 'nth' letter.

Results (Answers may vary due to random):

print(encrypt_string("0123456789", 2)) # Every other letter
M1M3M5M7M9

print(encrypt_string("0123456789", 3)) # Every third letter
D12D45D78D

I hope this helped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM