Frank Hayward
Frank Hayward

Reputation: 1137

Convert all letters to uppercase except those following a backslash

I have the following 8 bit hex string \x00\x13\xa2\x00@\n!\x1c The desired output is '\x00\x13\xA2\x00@\n!\x1C'

I need to do this by changing the all letters to caps except for those following a \

I tried to do this by making the entire string into Caps and making the N's and X's lowercase, but it far from ideal

import re
mysourceaddrlong = ( repr(data['source_addr_long'])[1:-1] ) 

which outputs \x00\x13\xa2\x00@\n!\x1c

 mysourceaddrlongUPPERCASE = mysourceaddrlong.upper()
    mysourceaddrlongFIXED = re.sub('[XN]+', lambda m: m.group(0).lower(), mysourceaddrlongUPPERCASE)

Upvotes: 1

Views: 198

Answers (1)

Bhargav Rao
Bhargav Rao

Reputation: 52151

Yoou do not need a RegEx for this at all. You can just use str functions

>>> mysourceaddrlong = r"\x00\x13\xa2\x00@\n!\x1c"
>>> "\\".join([(i[0]+i[1:].upper()) for i in mysourceaddrlong.split('\\') if i])
'x00\\x13\\xA2\\x00@\\n!\\x1C'

Combine the generator expression with a join, and it will work out for you

EDIT

Add a \ in front if you want it to be so

e.g:

str = 'x00\\x13\\xA2\\x00@\\n!\\x1C' # what you get
str = "\\"+str

Upvotes: 5

Related Questions