Python论坛  - 讨论区

标题:[python-chinese] 大家帮我看看int函数

2006年01月09日 星期一 20:34

Jay wz12 at yeah.net
Mon Jan 9 20:34:09 HKT 2006

是和道理呢?为什么不能转化到二进制?三进制?
>>> int('98',2)
Traceback (most recent call last):
  File "", line 1, in ?
ValueError: invalid literal for int(): 9
>>> int('98',3)
Traceback (most recent call last):
  File "", line 1, in ?
ValueError: invalid literal for int(): 9
......etc......
>>> int('98',9)
Traceback (most recent call last):
  File "", line 1, in ?
ValueError: invalid literal for int(): 9
>>> int('98',10)
98
>>> int('98',11)
107
>>> int('98',12)
116
>>>
文档:
      int( [x[, radix]]) 

  Convert a string or number to a plain integer. If the argument is a string, it must contain a possibly signed decimal number representable as a Python integer, possibly embedded in whitespace. The radix parameter gives the base for the conversion and may be any integer in the range [2, 36], or zero. If radix is zero, the proper radix is guessed based on the contents of string; the interpretation is the same as for integer literals. If radix is specified and x is not a string, TypeError is raised. Otherwise, the argument may be a plain or long integer or a floating point number. Conversion of floating point numbers to integers truncates (towards zero). If the argument is outside the integer range a long object will be returned instead. If no arguments are given, returns 0. 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.exoweb.net/pipermail/python-chinese/attachments/20060109/ee808581/attachment.htm

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2006年01月09日 星期一 20:44

limodou limodou at gmail.com
Mon Jan 9 20:44:52 HKT 2006

在06-1-9,Jay <wz12 at yeah.net> 写道:
>
>
> 是和道理呢?为什么不能转化到二进制?三进制?
> >>> int('98',2)
> Traceback (most recent call last):
>    File "", line 1, in ?
> ValueError: invalid literal for int():  9
> >>> int('98',3)
> Traceback (most recent call last):
>    File "", line 1, in ?
> ValueError: invalid literal for int():  9
> ......etc......
> >>> int('98',9)
> Traceback (most recent call last):
>    File "", line 1, in ?
> ValueError: invalid literal for int():  9
> >>> int('98',10)
> 98
> >>>  int('98',11)
> 107
> >>> int('98',12)
> 116
> >>>
> 文档:
>
>      int(     [x[,        radix]])    Convert a string or number to a plain integer. If the argument is a    string, it must contain a possibly signed decimal number representable as a    Python integer, possibly embedded in whitespace. The radix    parameter gives the base for the conversion and may be any integer in the    range [2, 36], or zero. If radix is zero, the proper radix is    guessed based on the contents of string; the interpretation is the same as for    integer literals. If radix is specified and x is not a    string, TypeError is raised. Otherwise, the argument    may be a plain or long integer or a floating point number. Conversion of    floating point numbers to integers truncates (towards zero). If the argument    is outside the integer range a long object will be returned instead. If no    arguments are given, returns 0.
>

你可能理解错了。int是将一个其它进制的数转为一个计算机的整数,可以认为是2进制数。而不是将一个10进制数转成要求的进制数。

比如:0x10是16进制,转成10进制为16。那么int("10", 16)为16。说明是将"10"按16进制转为整数。而int("98",
2)是表示将2进制的"98"转为整数,而98不是一个合法的二进制数。其它的出错也是如此。


--
I like python!
My Blog: http://www.donews.net/limodou
NewEdit Maillist: http://groups.google.com/group/NewEdit

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2006年01月09日 星期一 21:11

Andelf andelf at gmail.com
Mon Jan 9 21:11:15 HKT 2006

*int*( [x[, radix]])radix是进制么?

在06-1-9,Jay <wz12 at yeah.net> 写道:
>
>  是和道理呢?为什么不能转化到二进制?三进制?
> >>> int('98',2)
> Traceback (most recent call last):
>   File "", line 1, in ?
> ValueError: invalid literal for int(): 9
> >>> int('98',3)
> Traceback (most recent call last):
>   File "", line 1, in ?
> ValueError: invalid literal for int(): 9
> ......etc......
> >>> int('98',9)
> Traceback (most recent call last):
>   File "", line 1, in ?
> ValueError: invalid literal for int(): 9
> >>> int('98',10)
> 98
> >>> int('98',11)
> 107
> >>> int('98',12)
> 116
> >>>
> 文档:
>   *int*( [x[, radix]])
>  Convert a string or number to a plain integer. If the argument is a
> string, it must contain a possibly signed decimal number representable as a
> Python integer, possibly embedded in whitespace. The radix parameter gives
> the base for the conversion and may be any integer in the range [2, 36], or
> zero. If radix is zero, the proper radix is guessed based on the contents
> of string; the interpretation is the same as for integer literals. If
> radix is specified and x is not a string, TypeError is raised. Otherwise,
> the argument may be a plain or long integer or a floating point number.
> Conversion of floating point numbers to integers truncates (towards zero).
> If the argument is outside the integer range a long object will be returned
> instead. If no arguments are given, returns 0.
>
> _______________________________________________
> 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/20060109/baf80e87/attachment-0001.html

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2006年01月10日 星期二 11:20

Qiangning Hong hongqn at gmail.com
Tue Jan 10 11:20:13 HKT 2006

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

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

如下红色区域有误,请重新填写。

    你的回复:

    请 登录 后回复。还没有在Zeuux哲思注册吗?现在 注册 !

    Zeuux © 2025

    京ICP备05028076号