2017-09-26 69 views
-1

我有两个字符串,让我们说:蟒蛇 - 查找替换词在两个字符串

a = "Hello, I'm Daniel and 15 years old." 
b = "Hello, I'm (name) and (age) years old." 

,现在我想蟒蛇找到替代词。它可以是这样的:

{"name": "Daniel", "age": "15"} 

我从来没有找到解决方案!非常感谢您的帮助!

+1

欢迎StackOverflow上。请阅读[如何提问](https://stackoverflow.com/help/how-to-ask),并包含您尝试过的内容。 – Antimony

+0

问题描述需要更多细节。 “模板”字符串是否有显示替换名称的括号?这两个字符串保证在其他地方都是相同的吗?保证替换是一个单词,没有空格或其他标点符号?模板字符串中的名称是否保证不同?等等。这样的细节在像这样的问题中很重要。 –

回答

3

可以使用zip()str.split()和字符切片(从密钥移除()):

res = {v[1:-1]: k for k, v in zip(a.split(), b.split()) if k !=v} 

str.split()用于分开上空白的每个字符串。

输出:

>>> res 
{'name': 'Daniel', 'age': '15'} 
+0

哇感谢这个非常快速的答案它帮助!我会接受你的答案! – Frostie

0

使用python3可以格式化与来自字典中的值的字符串。

"Hello, I'm {name} and {age} years old.".format(**{"name": "Daniel", "age": "15"})

c = {"name": "Daniel", "age": "15"} "Hello, I'm {name} and {age} years old.".format(**c)

另外,如果你问如何提取这些值,你会发现使用正则表达式的值:

import re 
regularExpression = "^Hello, I'm (.*) and ([0-9]*).*" 
input = "Hello, I'm Daniel and 15 years old." 
match = re.search(regularExpression,input) 
result = {"name": match.group(1), "age": match.group(2)}