How to convert a raw string r'\xdd' to '\xdd' more gracefully?

Jach Feng jfong at ms4.hinet.net
Thu Dec 8 21:05:02 EST 2022


Jach Feng 在 2022年12月7日 星期三上午10:23:20 [UTC+8] 的信中寫道:
> s0 = r'\x0a' 
> At this moment it was done by 
> 
> def to1byte(matchobj): 
> ....return chr(int('0x' + matchobj.group(1), 16)) 
> s1 = re.sub(r'\\x([0-9a-fA-F]{2})', to1byte, s0) 
> 
> But, is it that difficult on doing this simple thing? 
> 
> --Jach
The whold story is,

I had a script which accepts an argparse's positional argument. I like this argument may have control character embedded in when required. So I make a post "How to enter escape character in a positional string argument from the command line? on DEC05. But there is no response. I assume that there is no way of doing it and I have to convert it later after I get the whole string from the command line.

I made this convertion using the chr(int(...)) method but not satisfied with. That why this post came out.

At this moment the conversion is done almost the same as Peter's codecs.decode() method but without the need of importing codecs module:-)

def to1byte(matchobj):
....return matchobj.group(0).encode().decode("unicode-escape")


More information about the Python-list mailing list