代码之家  ›  专栏  ›  技术社区  ›  Python learner Shaavin

如何在python中使用for循环替换字符串中的字符?

  •  0
  • Python learner Shaavin  · 技术社区  · 3 年前

    我正在尝试制作一个代码,找到特殊字符并将其替换为 * .
    例如:

    L!ve l@ugh l%ve
    

    这应该随着时间的推移而改变

    L*ve l*ugh l*ve
    

    这就是我到目前为止所尝试的

    a = input()
    spe = "+=/_(*&^%$#@!-.?)"
    for i in a:
        if i in spe:
            b = a.replace(i,"*")
        else:
            b = i
            print(b,end="")
    

    这会返回类似这样的结果

    Lve lugh lve
    

    为什么我会变成这样?
    如何解决这个问题?

    4 回复  |  直到 3 年前
        1
  •  3
  •   Obaskly    3 年前

    一个简单的方法:

    import string
    
    all_chars = string.ascii_letters
    
    a = 'L!ve l@ugh l%ve'
    
    for item in a:
        if item ==' ':
            pass
        elif item not in all_chars:
            item='*'
            
        print(item, end="")
    
        2
  •  2
  •   mozway    3 年前

    你试图修改整个字符串,而你应该只处理字符。

    修改代码时,这将是:

    a = '(L!ve l@ugh l%ve)'
    spe = set("+=/_(*&^%$#@!-.?)") # using a set for efficiency
    
    for char in a:
        if char in spe:
            print('*', end='')
        else:
            print(char, end='')
    

    输出: *L*ve l*ugh l*ve*

    更具蟒蛇风格的方式是:

    spe = set("+=/_(*&^%$#@!-.?)")
    print(''.join(['*' if c in spe else c  for c in a]))
    
        3
  •  2
  •   daemon    3 年前

    当到达if语句并且if满足条件时,它进入分支并执行。如果您只想打印可以运行的语句:

    a = input()
    spe = "+=/_(*&^%$#@!-.?)"
    for i in a:
        if i in spe:
            b = "*"
            print(b)
        else:
            b = i
            print(b,end="")
    

    但也可以将其保存为字符串

    a = input()
    new_string = ""
    spe = "+=/_(*&^%$#@!-.?)"
    for i in a:
        if i in spe:
            new_string += "*"
        else:
            new_string += i
    print(new_string)
    
        4
  •  1
  •   ramzeek    3 年前

    作为另一种选择,您可以尝试使用正则表达式。以下是两种可能的方法,具体取决于您想要如何定义字符集:

    import re
    print(re.sub('[^a-zA-Z\d\s]', '*', "L!ve l@ugh l%ve"))
    print(re.sub("[$&+,:;=?@#|'<>.^*()%!-]", '*', "L!ve l@ugh l%ve"))
    # L*ve l*ugh l*ve
    
        5
  •  0
  •   Kendle    3 年前

    脚本中有两个问题:

    • 如果发现特殊字符,则将其替换为b,而不是I
    • 只有在找不到特殊字符时才能打印。
      尝试:
    a = "L!ve l@ugh l%ve"
    spe = "+=/_(*&^%$#@!-.?)"
    for i in a:
        if i in spe:
            b = i.replace(i,"*")
        else:
            b = i
        print(b,end="")
    

    或者,当我们替换原始字符串中的字符时,我们可以在末尾打印它:

    a = "L!ve l@ugh l%ve"
    spe = "+=/_(*&^%$#@!-.?)"
    for i in a:
        if i in spe:
            b = a.replace(i,"*")
        else:
            b = a
    print(b)