how can I subclass a string (str)?

Loic fejoz loic at fejoz.net
Wed Aug 14 10:11:38 CEST 2002


Loic fejoz <loic at fejoz.net> wrote:
> Jason R. Coombs <jaraco at spamblocker.sandia.gov> wrote:
>> [...]
>> BinaryString( '\x33\x22\xAB' ).HexRepr() == '0x3322ab'
>> and
>> repr( BinaryString().SetHexRepr( '0x3322AB' ) ) == '\x33\x22\xab'  #
>> 0x prefix is optional
>> [..]
>> Perhaps my approach to this problem is all wrong.  Are there any
>> suggestions for creating an elegant solution to the problem
>> described?
>>
>> Thanks much,
>> Jason
>
> what about the attach code ?
> cheers,

seems better to copy it...

import UserString
import string
import re

class BinaryString(UserString.UserString):
    def __repr__(self):
        return self.hexRepr()

    def __str__(self):
        return self.hexRepr()

    def hexRepr(self,groupBy = -1):
        ch = '0x'
        i = 0
        for char in self.data:
            ch = ch + hex(ord(char))[2:] #remove '0x'
            i = i + 1
            if i == groupBy:
                ch = ch + ' '
                i = 0
        return ch

    def setHexRepr(self,hexRepr):
        ch = ''
        if hexRepr[:2] == '0x':
            hexRepr = hexRepr[2:]
        hexRepr = string.replace(hexRepr,' ','')
        tokens = re.split('([0-9a-fA-F][0-9a-fA-F])',hexRepr)
        for tok in tokens:
            if tok:
                ch = ch + chr(int(tok,16))
        self.data = ch

    def getString(self):
        return self.data


if __name__=="__main__":
    ch = BinaryString('ab\x10\xCF\xFFc')
    print ch
    print ch.hexRepr(2)
    print ch.getString()
    ch1 = BinaryString('')
    print ch1
    ch1.setHexRepr('0xFFEEDDCCBBAA10')
    print ch1
    ch2 = BinaryString('')
    ch2.setHexRepr('0x6465 3132')
    print ch2
    print ch2.getString()

--
Loïc





More information about the Python-list mailing list