【问题标题】:Python replace multiple substrings in a stringPython替换字符串中的多个子字符串
【发布时间】:2021-06-13 22:01:57
【问题描述】:

我有一条短信:“{name} 喜欢 {post}”。我根据来自 db 的 {} 中的值获取数据。然后我得到一个数组中的值,比如一个数据的 ["John", "515335"]。

我不知道我会在字符串中得到多少变量。也会是1或3。 (但要替换的内容数量和值将相同)

那么,替换该字符串中的值的最佳方法是什么?

我试过了:

for i in range(len(subContentArr)):
              content = re.sub(subContentArr[i], valuesArr[i], content, flags=re.IGNORECASE)

但我得到 local variable 'content' referenced before assignment 。 (内容是我用大括号得到的文本)

预期输出:“约翰喜欢 515335”

【问题讨论】:

    标签: python python-3.x django regex string


    【解决方案1】:

    如果 ab 是您数据库的输入,您可以像这样创建您想要的输出 d

    import re
    
    a = "{name} likes {post}"
    b = ['John', '515335']
    
    c = re.sub(r'\{[^}]+\}', '{}', a)
    
    d = c.format(*b)
    

    基本上c 将是您输入字符串的修改版本,它将占位符简化为{},然后我们可以使用.format() 将占位符替换为相同顺序的值。

    【讨论】:

      猜你喜欢
      • 2016-09-10
      • 1970-01-01
      • 2017-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-01
      • 2014-10-12
      相关资源
      最近更新 更多