代码之家  ›  专栏  ›  技术社区  ›  1chenar

替换python中的特定表达式

  •  0
  • 1chenar  · 技术社区  · 2 年前

    我想替换一个字符串 "${}" 具有 "*" 在python中。 例如,替换:

    "This is ${ali} from team"
    

    具有

    "This is * from team"
    

    我已经试过了,但不起作用:

    re.sub("^$.*}$", "*",str)
    
    3 回复  |  直到 2 年前
        1
  •  1
  •   codester_09 aka Sharim    2 年前
    import re
    s = "This is ${ali} from team ${asda} "
    
    s = re.sub(r'\${.[^}]+}','*',s)
    print(s)
    

    输出

    This is * from team *
    

    肾盂道

    s = "This is ${ali} from team ${asd}"
    
    s = list(s)
    try:
        while '$' in s and '}' in s:
            s[s.index('$'):s.index('}')+1] = '*'
    except ValueError:
        pass
    s = ''.join(s)
    print(s) # → This is * from team *
    
    
        2
  •  0
  •   llRub3Nll    2 年前

    试试下面的F-string方法, '''

    • =某物

    打印(f“打印中间有{*}的文本”) '''

        3
  •  0
  •   Piotr Ostrowski    2 年前

    使用正则表达式可以做到这一点。

    import re
    
    
    test_str = "This is ${ali} from team"
    sub = "*"
    
    regex = r"\$\{[^;]*\}"
    result = re.sub(regex, sub, test_str, 0)
    
    print(result)
    // "This is * from team"