Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在字符串中重复随机字母(python)_Python_Python 3.x - Fatal编程技术网

在字符串中重复随机字母(python)

在字符串中重复随机字母(python),python,python-3.x,Python,Python 3.x,在python中工作,希望创建一个函数,该函数接受一个字符串并在该字符串中重复一个随机字母“n”次。例如: Input=“溢出” 函数将返回“overflow”或“oveerflow” 到目前为止,除了将字符串拆分为数组之外,没有其他代码。请尝试以下方法: import random def repeat_random(n, input): random_char = input[random.randint(0,len(input)-1)] return input.repl

在python中工作,希望创建一个函数,该函数接受一个字符串并在该字符串中重复一个随机字母“n”次。例如:

Input=“溢出”

函数将返回“overflow”或“oveerflow”


到目前为止,除了将字符串拆分为数组之外,没有其他代码。

请尝试以下方法:

import random

def repeat_random(n, input):
    random_char = input[random.randint(0,len(input)-1)]
    return input.replace(random_char, random_char*n)
打印(随机重复(3,“溢出”))

卵流


难道我们都不喜欢巴迪·鲍勃自制的饼干吗

import random
def multi(count,stringEx):
    randChar = random.choice(stringEx)
    amount = randChar * count
    return stringEx.replace(randChar,amount)
print(multi(3,'stackoverflow'))
  • 首先,选择一个随机字母。
  • 把它乘以“count”。
  • 使用replace将“amount”添加到“stringEx”中。 输出

    stackoverflowww
    
    试试这个

    import random
    x=input("Word: ")  #=== Input for user
    word=[d for d in x] #=== Create a list of every character in the string
    rand=random.choice(word)  #==== Random choice of character from the list
    index=word.index(rand) #=== Get the index position of the character
    i=2
    for n in range(i): #=== Iterate till i=2
        word.insert(index+n,rand) #=== add the random letter after the index position of similar letter
    
    print("".join(word)) #=== Print the word by joining the characters
    

    你可以试试这样的方法:

    from random import seed, randint
    
    seed(42)
    
    def repeat_letter(n, inp):
        pos = randint(0, len(inp))
        return inp[:pos]+inp[pos]*n+inp[pos+1:]
    
    
    n = 3
    inp = "overflow"
    print(repeat_letter(n, inp))
    print(repeat_letter(n, inp))
    # ...
    print(repeat_letter(n, inp))
    
    结果是:

    ovvverflow
    oooverflow
    overffflow
    
    

    n
    是由输入决定的还是固定的?@Sujay它是固定的。即使你只有很少的代码,向社区表明你也在努力解决这个问题也是很重要的。如果随机字母出现在字符串的不同位置怎么办?每一个都应该复制吗?@JonSG gotcha将在未来完成,非常感谢!!工作得很好!嗯,我不知道。
    input
    是一个内置函数。请为变量使用其他名称