例如,我有一个字符串:
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的项存在于列表2中,则将其替换为相应的list2的项)字符串)?
list1 = ['a b', 'c d', 'e f', 'g h', 'i j']
list2 = ['a_b', 'c_d', 'e_f', 'g_h', 'i_j']
您可以将列表与配对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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句