【问题标题】:Simultaneously replace list of strings with a single value同时用单个值替换字符串列表
【发布时间】:2019-06-22 08:46:13
【问题描述】:

我想以 Python 的方式用单个字符串替换字符串列表。为了澄清我的意思,这段代码做了我想要的:

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')

会成功的。但是replace 方法只接受一个字符串作为输入。

有没有更 Pythonic 的方式(我想,一种没有 for 循环的方式)来执行这个操作?

提前致谢!

【问题讨论】:

    标签: python string python-2.7


    【解决方案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 以显示导致不同输出的情况

    【讨论】:

    • 不错!感谢您的回答,+1
    猜你喜欢
    • 2018-05-30
    • 1970-01-01
    • 2019-12-26
    • 2010-10-06
    • 1970-01-01
    • 1970-01-01
    • 2020-08-31
    • 2021-08-02
    • 1970-01-01
    相关资源
    最近更新 更多