[英]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? 我会如何在每次说完第3个字母后插入这封信? Ie String before: abcdef , String after: abcldefk. 即在字符串之前:abcdef,在字符串之后: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: 您可以使用str.join
, enumerate
起始索引等于1并取模:
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
: 如果您只想插入随机字母,则可以使用string.ascii_letters
和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. 我从Padraic的答案中得到启发,并想添加更多一点。
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. 这是每个'n'个字母的字符串“加密”(宽松使用)方法。
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. 希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.