【发布时间】:2018-09-27 22:04:59
【问题描述】:
我遇到了以下问题,想知道什么是解决它的优雅方法。 假设我们有两个字符串:
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"
我想要dict{food1:rice, food2:soup, food3:vegetables} 作为结果。
谁知道如何实现它?
编辑:
我认为我需要更强大的功能。
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() 或尝试拆分字符串的答案都行不通。没有规定将哪些字符用作字符串中的分隔符。
【问题讨论】:
-
不确定它是否会对某些答案产生影响,但我认为您需要处理具有复合名称的食物。即“蛤蜊浓汤”
-
@JLPeyret 你是对的,我不希望将字符串分成不同的部分,因为空格并不总是分隔符。
标签: python regex string python-3.x