【问题标题】:Python: Replace single character with multiple valuesPython:用多个值替换单个字符
【发布时间】:2020-10-08 18:05:48
【问题描述】:

我有一个带有“?”的字符串作为占位符。我需要遍历字符串并替换每个“?”与列表中的下一个值。

例如:

my_str = "Take the source data from ? and pass to ?;"
params = ['temp_table', 'destination_table']

这是我尝试过的,效果很好:

params_counter = 0
for letter in my_str:
    if letter == '?':
        # Overwrite my_str with a new version, where the first ? is replaced
        my_str = my_str.replace('?', params[params_counter], 1)
        params_counter += 1

问题是多次循环遍历字符串中的每个字母似乎相当慢。我的示例是一个简单的字符串,但实际情况可能是更长的字符串。

有什么更优雅或更有效的方法来实现这一点?

我看到this question,它比较相似,但他们使用字典并用多个值替换多个值,而不是我用多个值替换一个值的情况。

【问题讨论】:

  • Python 有一个内置的方法来完成这个任务。查看此问题的第一个答案:stackoverflow.com/questions/9452108/…
  • @PhilippeDixon true,但是如果我理解正确的话,.replace() 并没有给你多个值作为替代品......
  • 循环遍历字符串的每个字符是没有意义的。只需循环执行.replace();如果实际上没有要替换的'?',这不是错误。

标签: python string list replace


【解决方案1】:

你不需要迭代,replace会替换字符串的第一次出现:

一个聪明的解决方案是按您正在搜索的字符串进行拆分,然后使用长度相同的替换列表压缩列表,然后加入

list1 = my_str.split('?')
params = ['temp_table', 'destination_table']
zipped = zip(list1, params)
replaced = ''.join([elt for sublist in zipped for elt in sublist])

In [19]: replaced                                                               
Out[19]: 'Take the source data from temp_table and pass to destination_table'

您可以使用多个字符串,这会杀死您的方法:

my_str = "Take the source data from magicword and pass to magicword;
list1 = my_str.split('magicword') 
params = ['temp_table', 'destination_table'] 
zipped = zip(list1, params)
replaced = ''.join([elt for sublist in zipped for elt in sublist]) 
In [25]: replaced                                                               
Out[25]: 'Take the source data from temp_table and pass to destination_table'

请注意,如果您的参数短于搜索字符串的出现次数,则会将其删除

IN []my_str = "Take the source data from ? and pass to ?; then do again with ? and to ?"
Out[22]: 'Take the source data from temp_table and pass to destination_table'

另请注意,找到字符串后的最后一位被删除:(,类似于

replaced = ''.join([elt for sublist in zipped for elt in sublist] + [list1[-1]])

会成功的

【讨论】:

    【解决方案2】:

    虽然@E。 Serra 的答案是一个很好的答案,@jasonharper 的评论让我意识到有一个更简单的答案。非常简单,我很惊讶我完全错过了它!

    我应该循环遍历参数,而不是遍历字符串。这将允许我替换“?”的第一个实例使用我正在查看的当前参数。然后我覆盖字符串,让它在下一次迭代中正确执行。

    与发布的其他解决方案不同,它也不会切断我的字符串的结尾。

    my_str = "Take the source data from ? and pass to ?;"
    params = ['temp_table', 'destination_table']
    
    for item in params:
        query_str = query_str.replace('?', item, 1)
    

    【讨论】:

      猜你喜欢
      • 2021-06-08
      • 2014-06-03
      • 2013-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-29
      相关资源
      最近更新 更多