2006年01月10日 星期二 18:25
thank you all I understand. > > Jay wrote: > > 是和道理呢?为什么不能转化到二进制?三进制? > >>>> int('98',2) > > Traceback (most recent call last): > > File "", line 1, in ? > > ValueError: invalid literal for int(): 9 > > 你看看下面的例子: > > 二进制数字符串 -> 数值: > .>>> int('10101101', 2) > 173 > > 数值 -> 十六进制数字符串: > .>>> hex(173) > '0xad' > 或者 > .>>> '%x' % 173 > 'ad' > > 数值 -> 八进制数字符串: > .>>> oct(173) > '0255' > 或者 > .>>> '%o' % 173 > '255' > > 数值 -> 十进制数字符串: > .>>> str(173) > '173' > 或者 > .>>> '%d' % 173 > '173' > > 数值转到其他进制可能需要自己编写函数,ASPN上有一个现成的[1],抄在下面: > > [1] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/365468 > > def num_in_base(val, base, min_digits=1, complement=False, > digits="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"): > """Convert number to string in specified base > > If minimum number of digits is specified, pads result to at least > that length. > If complement is True, prints negative numbers in complement > format based on the specified number of digits. > Non-standard digits can be used. This can also allow bases greater > than 36. > """ > if base < 2: raise ValueError("Minimum base is 2") > if base > len(digits): raise ValueError("Not enough digits for base") > # Deal with negative numbers > negative = val < 0 > val = abs(val) > if complement: > sign = "" > max = base**min_digits > if (val > max) or (not negative and val == max): > raise ValueError("Value out of range for complemented format") > if negative: > val = (max - val) > else: > sign = "-" * negative > # Calculate digits > val_digits = [] > while val: > val, digit = divmod(val, base) > val_digits.append(digits[digit]) > result = "".join(reversed(val_digits)) > leading_digits = (digits[0] * (min_digits - len(result))) > return sign + leading_digits + result > > if __name__ == "__main__": > # Quick sanity check > for base in range(2, 37): > for val in range(-1000, 1000): > assert val == int(num_in_base(val, base), base) > > # Quick sanity check of complemented format > def comp(val, base, digits): > return num_in_base(val, base, digits, complement = True) > for base in range(2, 37): > for digits in range(1, 11): > limit = base ** digits > for val in range(-min(limit, 1000), 0): > assert limit + val == int(comp(val, base, digits), base) > for val in range(0, min(limit, 1000)): > assert val == int(comp(val, base, digits), base) > > > > -- > Qiangning Hong > http://hongqn.hn.org > Registered Linux User #396996 > _______________________________________________ > python-chinese > Post: send python-chinese at lists.python.cn > Subscribe: send subscribe to python-chinese-request at lists.python.cn > Unsubscribe: send unsubscribe to python-chinese-request at lists.python.cn > Detail Info: http://python.cn/mailman/listinfo/python-chinese > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://lists.exoweb.net/pipermail/python-chinese/attachments/20060110/8786b258/attachment-0001.html
Zeuux © 2025
京ICP备05028076号