替换字符串中的随机字符

huangapple go评论73阅读模式
英文:

Replacing random characters in string

问题

我有一个随机字符串单词,例如

word = graphic

我想要取这个单词,将其中的任意字母替换为下划线,并在它们之间添加空格,使输出看起来像这样

g _ a _ h _ c

下划线应该是每次不同单词时随机的。我该如何高效地实现这个目标?

英文:

I have a random string word for example

word = graphic

I want to take this word and and turn any random letters into underscore and put space in between

for the output to look something like this

g _ a _ h _ c

The underscore should be random for a different word each time. How can I do this efficiently

答案1

得分: 1

这是使用Python内置的random模块来实现的一种方法。这里的想法是随机选择要用下划线替换的单词中的字母的索引。

import random

def random_underscores(word, p=0.5):
    """
    随机在单词中的随机位置用下划线替换字母的函数。
    
    参数:
    word: str, 要替换字母的单词。
    p: float, 每个字符被替换的概率。默认值为0.5。
    """
    
    return ' '.join('_' if random.random() < p else char for char in word)

word = "graphic"
print(random_underscores(word))

这个脚本定义了一个名为random_underscores()的函数,它接受一个单词和一个概率p作为参数(默认值为0.5,因此平均来说会替换一半的字符)。

该函数使用列表推导式来迭代单词中的每个字符。对于每个字符,它生成一个介于0和1之间的随机数,如果该数字小于p,则用下划线替换字符。

您可以调整p的值以控制被替换的平均字母数。值为1.0将替换所有字母,值为0.0将不替换任何字母。

请记住,由于替换是随机的,每次使用相同的输入运行该函数时,都会得到不同的结果。

如果您希望确保至少有一个字符始终可见,您可以稍微修改函数以检查是否已替换了所有字符。如果是这样,它可以随机选择一个字符保持可见:

import random

def random_underscores(word, p=0.5):
    """
    随机在单词中的随机位置用下划线替换字母的函数,确保至少有一个字符可见。
    
    参数:
    word: str, 要替换字母的单词。
    p: float, 每个字符被替换的概率。默认值为0.5。
    """
    replaced = ['_' if random.random() < p else char for char in word]

    # 检查是否已替换了所有字符。如果是这样,随机选择一个字符保持可见
    if all(char == '_' for char in replaced):
        replaced[random.randint(0, len(word)-1)] = word[random.randint(0, len(word)-1)]
        
    return ' '.join(replaced)

word = "graphic"
print(random_underscores(word))
英文:

Here's a way to do this using Python's built-in random module. The idea here is to randomly select indices of the letters in the word to be replaced by an underscore.

import random

def random_underscores(word, p=0.5):
    &quot;&quot;&quot;
    Function to replace letters in a word with underscores at random places.
    
    Parameters:
    word: str, the word to replace letters in.
    p: float, probability of each character being replaced. Default is 0.5.
    &quot;&quot;&quot;

    
    return &#39; &#39;.join(&#39;_&#39; if random.random() &lt; p else char for char in word)

word = &quot;graphic&quot;
print(random_underscores(word))

This script defines a function random_underscores() that takes in a word and a probability p (default is 0.5, so on average half of the characters will be replaced).

The function uses a list comprehension to iterate over each character in the word. For each character, it generates a random number between 0 and 1, and if that number is less than p, it replaces the character with an underscore.

You can adjust the value of p to control the average number of letters that get replaced. A value of 1.0 will replace all letters, and a value of 0.0 will replace none.

Remember that because the replacement is random, you'll get different results each time you run the function with the same inputs.

If you want to ensure that at least one character is always visible, you can modify the function slightly to check if all characters have been replaced. If so, it can randomly select one character to remain visible:

import random

def random_underscores(word, p=0.5):
    &quot;&quot;&quot;
    Function to replace letters in a word with underscores at random places, ensuring at least one character remains.
    
    Parameters:
    word: str, the word to replace letters in.
    p: float, probability of each character being replaced. Default is 0.5.
    &quot;&quot;&quot;
    replaced = [&#39;_&#39; if random.random() &lt; p else char for char in word]

    # Check if all characters have been replaced. If so, randomly select one to remain
    if all(char == &#39;_&#39; for char in replaced):
        replaced[random.randint(0, len(word)-1)] = word[random.randint(0, len(word)-1)]
        
    return &#39; &#39;.join(replaced)

word = &quot;graphic&quot;
print(random_underscores(word))

答案2

得分: 0

I hope this will help you

from random import choice
word = "helloWorld"
word = "".join(["_" if choice([True, False]) else char for char in word])
print(word)
英文:

I hope this will helps you

from random import choice
word = &quot;helloWorld&quot;
word = &quot;&quot;.join([&quot;_&quot; if choice([True, False]) else char for char in word])
print(word)

答案3

得分: 0

以下是已翻译的代码部分:

from random import randint
def RandUnder(word):
  nofUnderscores = randint(1, len(word))
  for i in range(nofUnderscores):
    randPos = randint(0, len(word)-1)
    word[randPos] = "_"
  return word
word = "example"
print(" ".join(RandUnder(list(word))))
英文:

You can try this:

from random import randint
def RandUnder(word):
  nofUnderscores = randint(1, len(word))
  for i in range(nofUnderscores):
    randPos = randint(0, len(word)-1)
    word[randPos] = &quot;_&quot;
  return word
word = &quot;example&quot;
print(&quot; &quot;.join(RandUnder(list(word))))

huangapple
  • 本文由 发表于 2023年6月9日 01:50:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76434495.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定