【问题标题】:Replace parts of string that match items from one list with parts of string from another list one by one将与一个列表中的项目匹配的字符串部分替换为另一个列表中的字符串部分
【发布时间】:2021-04-19 23:19:32
【问题描述】:

例如,我有一个字符串:

string1 = 'a b c d e f g h i j'

我怎样才能让它看起来像这样:

string1 = 'a_b c_d e_f g_h i_j'

通过将 string1 的子字符串与 list1 中的项目进行匹配,然后用 list2 中的项目顺序替换匹配的子字符串(例如,通过检查 string1 中 list1 中的每个项目的存在,然后如果 list1 的项目将其替换为相应的 list2 的项目是否存在于字符串中)?

list1 = ['a b', 'c d', 'e f', 'g h', 'i j']
list2 = ['a_b', 'c_d', 'e_f', 'g_h', 'i_j']

【问题讨论】:

标签: python string list replace


【解决方案1】:

您可以将列表与zip 配对,然后在每一对上应用str.replace

list1 = ['a b', 'c d', 'e f', 'g h', 'i j']
list2 = ['a_b', 'c_d', 'e_f', 'g_h', 'i_j']
string1 = 'a b c d e f g h i j'

for search_text, replace_text in zip(list1, list2):
    string1 = string1.replace(search_text, replace_text)

# a_b c_d e_f g_h i_j

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    相关资源
    最近更新 更多