寻找将随机数插入字符串的所有可能性? (python)

Find every possibility to insert random number into a string? (python)

我是编程新手,为了进行练习,我需要创建一个列表,列出将随机数(从 0 到 9)插入字符串的所有可能性。可以在这个字符串的每个位置插入数字。

例如,我有字符串“Aht50rj2”,我需要找到在该字符串的任意位置(包括开头和结尾)插入一个数字的所有可能性。

到目前为止我还没有找到解决这个问题的方法。执行此操作的最佳方法是什么?

编辑: 输入是一个字符串(例如“Aht50rj2”) 预期的输出是一个包含所有可能方式的列表。 例如[“0Aht50rj2”、“Ah1t50rj2”、“Aht50rj29”、“Aht501rj2”等]

def possibility(word):
    possibilities = []
    for i in range(0,10):
        for j in range(len(word)+1):
            H  = [k for k in word]
            H.insert(j,str(i))
            possibilities.append(''.join(H))
    return possibilities

我不确定你的意思,但试试我的代码看看它是否有效:

import random   # import module "random"

example_string = input('Input a string: ') # Asks user to input a string

length_of_string= len(example_string)  # Counts how many characters there are in the string, it'll make sense trust me

example_list=[]  # Create a temporary list
example_list[:0]=example_string  # Get string, turns it into list

example_list.insert(random.randrange(0, length_of_string), str(random.randrange(0, 9)))  # Insert a random number into a random position of the list

list_into_string= ''.join(example_list)  # Get string, turns it into string
print(list_into_string)  # Print result

结果编号 1:

Input a string: Whosebug
sta1ckoverflow

结果编号 2:

Input a string: Whosebug
stacko8verflow

结果编号 3:

Input a string: Whosebug
stackoverfl5ow

您可以使用字符串长度循环,然后将 str(num) 替换为任何索引中的每个字符,如下所示:

import random
st = "Aht50rj2"
res = []
for idx in range(len(st)):
    r_c = random.choice(range(9))
    char = st[idx]
    res.append(st.replace(st[idx], str(r_c)))

print(res)

输出:(一个运行时)

['3ht50rj2', 'A6t50rj2', 'Ah050rj2', 'Aht20rj2', 'Aht54rj2', 'Aht506j2', 'Aht50r22', 'Aht50rj0']