Search code examples
python-2.7casing

Changing Case with Exception Specifically in between dollar signs


Input:

MECR-tree obtained using \textbf{MCAR-Miner} with $S_{\mathrm{U}}  = data$ 25{\%} and $S_{\mathrm{L}}  = string$ 12.5{\%}

Change it to Title Case but exempt the text within the $ signs.

Output should be:

Mecr-Tree Obtained Using \textbf{Mcar-Miner} With $S_{\mathrm{U}}  = data$ 25{\%} And $S_{\mathrm{L}}  = string$ 12.5{\%}

Solution

  • Here's an example that assumes that the $ character will always occur in pairs:

    sp = s.split('$')
    for i, seg in enumerate(sp):
        if i % 2 == 0:
            sp[i] = seg.title()
    
    print('$'.join(sp))
    

    Using a list comprehension:

    print(r'$'.join([seg.title() if not i % 2 else seg for i, seg in enumerate(s.split('$'))]))