【问题标题】:To replace the digits in the string with # and remove all the characters which are not digits用#替换字符串中的数字并删除所有不是数字的字符
【发布时间】:2020-05-25 15:00:41
【问题描述】:

用 '#' 替换特定字符,但没有发生替换。代码有什么问题?

输入:

A="234"

for i in range (len(A)):

  if (A[i].isdigit()):

    print(A[i])

    A.replace(A[i],"#");

print(A)

输出:

2
3
4
234

【问题讨论】:

  • 问题是你没有保存你的工作。试试这个:A = A.replace(A[i],"#") 。没有用;

标签: python string replace


【解决方案1】:

A.replace(A[i],"#") 只会返回另一个字符串,它不会覆盖原来的字符串。这样做来覆盖它:

A="234"

for i in range (len(A)):

  if (A[i].isdigit()):

    print(A[i])

    A = A.replace(A[i],"#");

print(A)

【讨论】:

    【解决方案2】:

    在 python 的内置 re 模块中使用正则表达式可能会更容易。然后你可以在两个正则表达式中做到这一点。

    re.sub(r'[^\d]', '', A)
    re.sub(r'\d', '#', A)
    

    【讨论】:

    • 如果您将第一个结果分配回A,这将起作用,但re.sub 不会就地编辑字符串。
    【解决方案3】:

    对于您询问的代码,@AnnZen (+1) 提供的建议是合理的,尽管我会折腾分号和额外的括号。我还会遍历字符串中的字符而不是它们的索引:

    for c in A:
        if c.isdigit():
            A = A.replace(c, "#")
    

    就解决完整问题(即添加非数字消除)而言,我们实际上不需要replace()

    def convert(string):
        result = ''
    
        for character in string:
            if character.isdigit():
                result += "#"
    
        return result
    

    但是,如果我们想要使用replace(),这似乎也是一个使用defaultdict的机会:

    from collections import defaultdict
    
    dictionary = defaultdict(str, {digit: '#' for digit in "0123456789"})
    
    def convert(string):
        for character in string:
            string = string.replace(character, dictionary[character])
    
        return string
    

    我们可以添加一些测试代码来检查一下:

    if __name__ == "__main__":  # test code
        from random import choice, randint
        from string import ascii_letters, digits
    
        for tests in range(10):
            test_string = ''.join(choice(ascii_letters + digits) for _ in range(randint(10, 20)))
    
            print(repr(test_string), end=' -> ')
    
            test_string = convert(test_string)
    
            print(repr(test_string))
    

    输出

    > python3 test.py
    'RzfMD5w3LQO' -> '##'
    'NrFsFDDyOit593' -> '###'
    'TpURdM0PqTQtaPe3IeP' -> '##'
    'TN10mz39BukFNsgf' -> '###'
    'ghYfxDLrPSEG5GCO' -> '#'
    '9QAJ1PVyegMD' -> '#'
    'GOIgOmzpC1ysn4' -> '#'
    'LEdR2BafYi9paALgrN' -> '##'
    'L2hzkSQNkH2Gb' -> '##'
    'E6rnoGi2AamWW01R19' -> '####'
    >
    

    @duckboycool 的正则表达式想法有其优点,即使当前建议的实现没有。我们不需要两个模式匹配,只需要一个来消除非数字:

    import re
    
    def convert(string):
        return '#' * len(re.sub(r'\D', '', string))
    

    我的各种convert() 函数中的任何一个都应该适用于我上面的测试代码。

    【讨论】:

      猜你喜欢
      • 2014-08-26
      • 1970-01-01
      • 2013-02-25
      • 1970-01-01
      • 1970-01-01
      • 2012-10-10
      • 2010-12-01
      • 1970-01-01
      • 2021-06-08
      相关资源
      最近更新 更多