Home > Mobile >  Python uppercase the entire string except letters which are within quotes but after colon
Python uppercase the entire string except letters which are within quotes but after colon

Time:02-08

I have string in python like

INS_hdr:"To:abc.micky.com|From:xyz.micky.com",TRANSFERTARGET:"B_london"

need to convert to like this

INS_HDR:"TO:abc.micky.com|FROM:xyz.micky.com",TRANSFERTARGET:"B_LONDON"

I dont want to convert string to uppercase based on colon, as i use multiple colon in string, need to convert uppercase based on colon which appear inside quotes

CodePudding user response:

I would just brute force it, iterating and keeping track of the state (in quote, in quote after colon, not in quote).

CodePudding user response:

Given your particular example, you could re.split on : with a non quoted word, then loop over the groups to determine which ones to make upper case based on the leading colon:

import re

s = 'INS_hdr:"To:abc.micky.com|From:xyz.micky.com",TRANSFERTARGET:"B_london"'

''.join(x.upper() if not x.startswith(':') else x 
        for x in re.split('(:[^"|] )', s))

output:

INS_HDR:"TO:abc.micky.com|FROM:xyz.micky.com",TRANSFERTARGET:"B_LONDON"
  •  Tags:  
  • Related