如何在字符串的特定位置添加随机生成的字符? [英] How to add randomly generated characters in specific locations in a string?

查看:42
本文介绍了如何在字符串的特定位置添加随机生成的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个需要我从文件中读取字符串的问题,并且:

I am working on a problem that requires me to read a string from the file and:

  1. 反转它
  2. 将定义整数加密强度.有可能设置为 0 到 255 之间的任何整数值.
  3. 根据加密强度的大小,会随机插入一些字母或数字在步骤 1 中反转字符串中的每个字母之间.

例如,如果强度设置为 1,则单词 hello 可以加密为 oxlal9elh.

再举个例子,如果强度为2,可以将hello这个词加密为oxil4hlrce6rh.

Another example, if the strength is 2, the word hello can be encrypted to oxil4hlrce6rh.

我的代码总体运行良好,但问题是我每次都会在字符串的字母之间插入重复的随机字符.

My code works overall fine, but the problem is I get repeated random characters inserted between the letters of string, every time.

这是我的代码,请帮助我识别错误.

Here's my code, kindly help me identify the error.

代码

def encrypt():
    data = "hello"
    content = data[::-1]

    encryption_str = 2
    
    characters = string.ascii_uppercase +string.ascii_lowercase+ 
    string.digits
    
    
    res = (random.choice(characters).join(content[i:i + encryption_str] for i 
    in range(0, len(content)))) #I am stuck here
    
    print(res)
encrypt()

输出

推荐答案

这会正常工作:

import string, random
def encrypt():
    data = "hello"
    content = data[::-1]

    encryption_str = 2

    characters = string.ascii_uppercase +string.ascii_lowercase+string.digits
    res = ""
    res+=content[0]
    for i in range(1,len(content)):
        for j in range(encryption_str):
            res+=random.choice(characters)
        res+=content[i]

    print(res)
encrypt()

输出

oLal5ilWremph

这篇关于如何在字符串的特定位置添加随机生成的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆