Search code examples
python-3.xstringrobotframeworkregexp-replace

Replace a string's character other than first two and last two characters with asterik in Robot Framework using regexp


What is pattern used to replace a string's character in Robot framework except that my first two and last two characters alone are retained and only all others characters are replaced.

Example:

My Input: RAHMAN/MD SANDID MSTR CHD

My Output: RA*********************HD

Please help on this.


Solution

  • You can do this:

    def starify(string):
        if len(string) <= 4:
            return string
        head = string[:2]
        tail = string[-2:]
        middle = "*" * (len(string) - 4)
        return head + middle + tail
    

    note that you will also have to define what do do when the string is too short (in this case I return as-is, but you might want to raise an exception, or turn the whole sting into * or something.