Search code examples
pythonpython-re

Is there a simpler way in python


I did the following to get from P13 to {P}{13}

import re

txt  = "P13"
x = re.search("[A-T]", txt )
y = re.split("[A-T]", txt )
txt  = "{" + x.group() + "}" + "{" + y[1] + "}"

It is working and gives what I want. But I'm wondering if there's an easier way.


Solution

  • You can try regex replace

    out = re.sub('([A-T]+)(\d+)', r'{\1}{\2}', txt)
    
    $ print(out)
    
    {P}{13}
    

    Explanation:

    • 1st Capturing Group ([A-T]+)

      Match a single character present in the list [A-T] one and unlimited times

    • 2nd Capturing Group (\d+)

      \d matches a digit (equivalent to [0-9]) and + matches the previous token between one and unlimited times