【问题标题】:String Replacement with Array of Strings用字符串数组替换字符串
【发布时间】:2014-03-21 17:37:52
【问题描述】:

假设我有一个字符串 s

s = "?, ?, ?, test4, test5"

我知道有三个问号,我想用下面的数组相应地替换每个问号

replace_array = ['test1', 'test2', 'test3']

获得

output = "test1, test2, test3, test4, test5"

Python 中是否有类似s.magic_replace_func(*replace_array) 之类的函数可以实现预期目标?

谢谢!

【问题讨论】:

    标签: python string list replace


    【解决方案1】:

    试试这个:

    s.replace('?', '{}').format(*replace_array)
    => 'test1, test2, test3, test4, test5'
    

    更好的是,如果您将? 符号替换为{} 占位符,您可以直接调用format(),而无需先调用replace()。之后,format() 会处理一切。

    【讨论】:

      【解决方案2】:

      还有一个带有函数方法的正则表达式——它只扫描字符串一次,在适应替换模式方面更灵活,不可能与现有的格式化操作冲突,如果不够,可以更改以提供默认值有替代品...:

      import re
      
      s = "?, ?, ?, test4, test5"
      replace_array = ['test1', 'test2', 'test3']
      res = re.sub('\?', lambda m, rep=iter(replace_array): next(rep), s)
      #test1, test2, test3, test4, test5
      

      【讨论】:

      • 这就是我的想法,虽然因为我不喜欢正则表达式,所以我选择了to_replace = iter(replace_array)''.join([c if c != '?' else next(to_replace) for c in s])。我不得不承认,使用正则表达式更适合被替换的模式。
      【解决方案3】:

      使用带有限制的str.replace(),然后循环:

      for word in replace_array:
          s = s.replace('?', word, 1)
      

      演示:

      >>> s = "?, ?, ?, test4, test5"
      >>> replace_array = ['test1', 'test2', 'test3']
      >>> for word in replace_array:
      ...     s = s.replace('?', word, 1)
      ... 
      >>> s
      'test1, test2, test3, test4, test5'
      

      如果您的输入字符串不包含任何花括号,您还可以将花括号替换为 {} 占位符并使用 str.format()

      s = s.replace('?', '{}').format(*replace_array)
      

      演示:

      >>> s = "?, ?, ?, test4, test5"
      >>> s.replace('?', '{}').format(*replace_array)
      'test1, test2, test3, test4, test5'
      

      如果您的实际输入文本已经包含 {} 字符,您需要先转义这些字符:

      s = s.replace('{', '{{').replace('}', '}}').replace('?', '{}').format(*replace_array)
      

      演示:

      >>> s = "{?, ?, ?, test4, test5}"
      >>> s.replace('{', '{{').replace('}', '}}').replace('?', '{}').format(*replace_array)
      '{test1, test2, test3, test4, test5}'
      

      【讨论】:

        【解决方案4】:

        使用str.replace并将'?'替换为'{}',那么你可以简单地使用str.format方法:

        >>> s = "?, ?, ?, test4, test5"
        >>> replace_array = ['test1', 'test2', 'test3']
        >>> s.replace('?', '{}', len(replace_array)).format(*replace_array)
        'test1, test2, test3, test4, test5'
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-04-26
          • 1970-01-01
          • 2013-11-08
          • 1970-01-01
          • 2010-09-28
          • 1970-01-01
          • 2012-02-18
          相关资源
          最近更新 更多