【问题标题】:How do I remove multiple random characters from a string in python如何从python中的字符串中删除多个随机字符
【发布时间】:2021-02-28 03:54:32
【问题描述】:

我想出了以下代码,但不幸的是它只从我的字符串中删除了 1 个字符。

import random
string = 'HelloWorld!'
def remove_random_character(phrase):
        character_number = random.randint(0, len(phrase))
        remover = f'{phrase[:character_number - 1]}_{phrase[character_number:]}'
        for _ in range(8):
            sliced_phrase = remover
        print(sliced_phrase)
remove_random_character(string)

我认为 for 循环会解决这个问题,但不幸的是它没有。但每次循环时,它都会刷新sliced_phrase 变量。但我不知道如何存储循环的最后一个版本,以便对其进行编辑。那么我怎样才能从一个字符串中删除多个随机字符呢?

【问题讨论】:

  • 预期的字符串是什么?
  • 你的函数没有返回任何值。插入 return sliced_phrase 之后/而不是 print 语句。然后像这样调用函数:result = remove_random_character(string)

标签: python string for-loop random python-3.8


【解决方案1】:

您可以遍历字符串中的每个字母并决定是否需要删除它:

import random
string = 'HelloWorld!'
output = ''.join([s for s in string if random.random() < 0.7])

测试:

Heloold!
elloWld!
loWorld

【讨论】:

    【解决方案2】:
    import random
    
    def remove_random_char(string):
        char_index_to_remove = random.randint(0, len(string)-1)
        string = string.replace(string[char_index_to_remove], '', 1)
    
        return string
    
    string = 'HelloWorld!'
    times_to_iterate = 4 
    for i in range(times_to_iterate):
        string = remove_random_char(string)
    

    【讨论】:

      【解决方案3】:

      怎么样:

      import random
      def remove_random_character(phrase, n_remove):
          for num in random.sample(range(0, len(phrase)), n_remove):
              phrase = phrase[:num] + '_' + phrase[num + 1:]
          return phrase
      

      然后删除,比如说,3 个随机字符:

      string = 'HelloWorld!'
      new_phrase = remove_random_character(string, 3)
      

      【讨论】:

        【解决方案4】:
        import random
        phrase = 'HelloWorld!'
        num_of_missing_chars = 4
        def random_char_remover(string: str, num_missing_char: int):
            def index_remover(string: str):
                char_index_to_remove = random.randint(0, len(string)-1)
                string = string.replace(string[char_index_to_remove], '_', 1)
                return string
        
            for i in range(num_missing_char):
                string = index_remover(string)
            print(string)
        random_char_remover(phrase, num_of_missing_chars)
        

        谢谢大家,这是我在查看了您的所有答案并使用了所有答案后最终得到的。从我的角度来看,它可能有点简化,但我只使用我能理解的代码。 :)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-03-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多