strings problem

Andy Jewell andy at wild-flower.co.uk
Sat Jul 5 00:10:06 CEST 2003


On Friday 04 Jul 2003 6:41 pm, Jimmy verma wrote:
> Hello *.*
>
> Can you please tell me how can i have the output in no's, instead of string
> from this program:
>
> #/usr/bin/python
> import re
> import string
>
> def csNumEncode(num):
>     if(num>=-107 and num<=107):
>         return chr(num+139)
>     elif(num>=108 and num<=1131):
>         return chr(((num-108)/256)+247) + chr((num-108)%256)
>     else:
>         print 'do nothing'
>
> re_num = re.compile("\-?[0-9]+(\.[0-9]+)?")
>
>
> def CompileCS(source):
>   result=''
>   for tkn in re.split('[ \n\t]+', source):
>     print "Token: %s"%tkn
>     if re_num.match(tkn):
>         result = result + csNumEncode(string.atoi(tkn))
>     else:
>         raise SyntaxError, "%s is invalid operator"%tkn
>   return result
>
> src1 = '50  800'
>
> t = CompileCS(src1)
>
> print t
>
>
>
> The output is
>
> Token: 50
> Token: 800
> \275\371\264
>
>
> Instead of this i want the output should be in no's like this:
> bdF9B4
>
> Your suggestions will be welcomed.
>
> Thanks a lot.
>
> Regards,
> Jim
>
> _________________________________________________________________
> Looking for love? Yearning for friendship? http://www.msn.co.in/Romance/
> You're in the right place.

Jim, 

I think you want the hex() function:

>>> hex(0275)
'0xbd'
>>> hex(0275)+hex(0371)+hex(0264)
'0xbd0xf90xb4'
>>> hex(0275)[2:]+hex(0371)[2:]+hex(0264)[2:]
'bdf9b4'
>>> 

hex produces a string from a number, but puts '0x' in front.  I used 
hex(n)[2:]  to chop off the first 2 chars.

hope that helps
-andyj





More information about the Python-list mailing list