同时用单个值替换字符串列表

时间:2019-01-29 09:12:28

标签: python string python-2.7

我想以pythonic方式用单个字符串替换字符串列表。为了阐明我的意思,这段代码可以满足我的要求:

 glGenBuffers(1, &rectangle_VBO);

 glBindBuffer(GL_ARRAY_BUFFER, rectangle_VBO);
 glBufferData(GL_ARRAY_BUFFER, sizeof(rectangle_vertices), &rectangle_vertices[0][0], GL_STATIC_DRAW);

 // Initialize vertex array object.
 glGenVertexArrays(1, &rectangle_VAO);
 glBindVertexArray(rectangle_VAO);

 glBindBuffer(GL_ARRAY_BUFFER, rectangle_VBO);
 glVertexAttribPointer(LOC_POSITION, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), BUFFER_OFFSET(0));
 glEnableVertexAttribArray(0);
 glVertexAttribPointer(LOC_NORMAL, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), BUFFER_OFFSET(3 * sizeof(float)));
 glEnableVertexAttribArray(1);

 glBindBuffer(GL_ARRAY_BUFFER, 0);
 glBindVertexArray(0);

我会想像的是

my_string = 'abc'
list_strings = ['a', 'b']
for replace_string in list_strings:
    my_string = my_string.replace(replace_string, 'c')

会成功的。但是my_string = my_string.replace(list_strings, 'c') 方法仅接受字符串作为输入。

执行此操作是否还有更多的Python方式(我想是没有replace循环的方式)?

谢谢!

1 个答案:

答案 0 :(得分:1)

解决方案可能是使用正则表达式(请参见re.sub):

import re

my_string = 'abc'

list_strings = ['a', 'b']

pattern = '|'.join(list_strings)
output = re.sub(pattern, 'bc', my_string)
print(output)
#  bcbcc

注意:我将替换字符串修改为bc,以显示导致不同输出的情况