-1

I have two strings, let's say:

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

And now I want python to find the replaced words. It can be something like this:

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

I never found a solution! Thank you very much for your help!

Frostie
  • 77
  • 2
  • 10
  • 1
    Welcome to StackOverflow. Please read [How to Ask](https://stackoverflow.com/help/how-to-ask), and include details of what you have tried. – Antimony Sep 26 '17 at 20:45
  • The problem description needs more detail. Could the "template" string have parentheses other than the ones showing the names of the replacements? Are the two strings guaranteed to be identical everywhere other than those replacement sites? Is the replacement guaranteed to be a single word, with no space or other punctuation? Are the names in the template string guaranteed to be distinct? And so on. Such details are important in problems like this one. – Rory Daulton Sep 26 '17 at 21:03

2 Answers2

3

You can use zip() with str.split() and string slicing (to remove ( and ) from keys):

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

str.split() is used to split each string on whitespace.

Output:

>>> res
{'name': 'Daniel', 'age': '15'}
ettanany
  • 19,038
  • 9
  • 47
  • 63
0

Using python3 you can format the string with values from a dictionary.

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

or

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

Alternatively, if you are asking how to extract these values you could find the values using a regular expression :

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)}
Bill Oldroyd
  • 359
  • 2
  • 5