如何在Python中快速合并字符串

时间:2019-07-12 08:18:20

标签: python

我有这样的字符串:

strA = "Today is hot. My dog love hot dog, milk, and candy."
strB = "hot dog and bread"

我希望输出字符串像这样:

"Today is hot. My dog love hot dog and bread, milk, and candy."

不是

"Today is hot dog and bread. My dog love hot dog, milk, and candy."

我尝试使用str.find() 但这不适合。

if strA.find(strB) != -1:    
    x = strA.find(strB)
    listA = list(strA)
    listA.insert(x, strB)
    output = ''.join(listA)

2 个答案:

答案 0 :(得分:0)

strA = "My dog love hot dog, milk, and candy."
strB = "dog and bread"

strA = strA.replace('dog,',strB);
print(strA);

这不是动态解决方案。但可以解决这个问题

答案 1 :(得分:0)

您可以进行反向查找并返回最匹配的结果。

strA = "Today is hot. My dog love hot dog, milk, and candy."
strB = "hot dog and bread"

def replace_method(string_a,string_b):
    s = string_b.split()
    for i in reversed(range(len(s)+1)):
        if " ".join(s[:i]) in string_a:
            return string_a.replace(" ".join(s[:i]),string_b)

print (replace_method(strA,strB))

结果:

Today is hot. My dog love hot dog and bread and cheese, milk, and candy.
相关问题