【问题标题】:Find every possibility to insert random number into a string? (python)找到将随机数插入字符串的所有可能性? (Python)
【发布时间】:2021-10-30 11:19:20
【问题描述】:

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

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

到目前为止,我无法找到解决此问题的方法。最好的方法是什么?

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

【问题讨论】:

  • 您能否提供输入和预期输出?

标签: python string list insert numbers


【解决方案1】:
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

【讨论】:

  • 非常感谢!这正是我想要的!
【解决方案2】:

您可以使用字符串长度进行循环,然后将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']

【讨论】:

    【解决方案3】:

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

    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: stackoverflow
    sta1ckoverflow
    

    结果编号 2:

    Input a string: stackoverflow
    stacko8verflow
    

    结果编号 3:

    Input a string: stackoverflow
    stackoverfl5ow
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-07
      • 1970-01-01
      • 1970-01-01
      • 2018-09-20
      • 2011-05-26
      • 1970-01-01
      相关资源
      最近更新 更多