Home > Software engineering >  How to give a placeholder for string so that it matches with other in python
How to give a placeholder for string so that it matches with other in python

Time:06-02

I am working on a project where i am getting a string from a client. I want to match this string with the expected_string.

So suppose my client gives : your name is: Mudit, Hello I want my expected_string to be something like your name is: <any_name>, Hello

And I want to assert client_string == expected_string.

I cant figure out a way to do this.

If

client_string = "your name is Mudit"

and

expected_string = "your name is"

I couldve gone with

assert expected_string in client_string

But how to do this if the variable is somewhere in the middle. How do I assert.

CodePudding user response:

Why not check that client_string begins with expected_string? The rest of the logic is up to you to implement. https://www.w3schools.com/python/ref_string_startswith.asp

Edit: To use patterns, regex:

import re
pattern = r'your name is (\w ) and your age is (\d ) years'
result = pattern.search(your_string)
valid = result is not None
if valid:
    print(result.groups())

https://www.geeksforgeeks.org/python-regex/

  • Related