我看到了以下问题,想知道解决它的优雅方式是什么。 假设我们有两个字符串:
string1 = "I love to eat $(fruit)"
string2 = "I love to eat apples"
这些字符串的唯一区别在于
$(fruit)
和 apples
。
因此,我可以找到水果是苹果,然后返回一个 dict{fruit:apples}
。另一个例子如下:
string1 = "I have $(food1), $(food2), $(food3) for lunch"
string2 = "I have rice, soup, vegetables for lunch"
我希望得到一个字典{food1:米饭,food2:汤,food3:蔬菜}作为结果。
有没有好的想法来实现它?
编辑:
我认为需要使函数更加强大。
ex.
string1 = "I want to go to $(place)"
string2 = "I want to go to North America"
result: {place : North America}
ex.
string1 = "I won $(index)place in the competition"
string2 = "I won firstplace in the competition"
result: {index : first}
这个规则是:将字符串的不同部分映射为一个字典
所以我猜,使用str.split()或尝试拆分字符串的所有答案都不会起作用。没有规定字符串中要使用哪些字符作为分隔符。