Search code examples
pythonstringwords

python - Find replaced words in two strings


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!


Solution

  • 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'}