繁体   English   中英

Python字符串索引错误?

[英]Python string indexing bug?

我在Python字符串索引中遇到了一个有趣的行为,我认为这可能是一个错误。

我的代码的目的是执行一系列操作,以将十六进制字符串转换为二进制(12位)并获取二进制字符串的子集(10 LSB)

提供我期望的结果的代码如下所示:

def test (hex):
    print (bin(int(hex,16))[2:].zfill(12)[3:12])

如果输入“ 1”,即十六进制=“ 1”

bin(int(hex,16))按预期返回0b1

bin(int(hex,16))[2:]删除前导0b并返回1按预期工作[2:]给出第三个字符和onwords

bin(int(hex,16))[2:].zfill(12)返回0000_0000_0001 (为说明目的添加了“ _”)

现在出现了有趣的部分,为了获得10 LSB,即一个人将使用的第3至第12个字符

bin(int(hex,16))[2:].zfill(12)[2,11]

但是,似乎我不得不使用bin(int(hex,16))[2:].zfill(12)[3,12]来获取00_0000_0001 ,这似乎表明索引以某种方式变为基于1而不是基于0.zfill(12)

结果是使用Python 3.4.1获得的

任何建议表示赞赏!

这是测试代码:

def test (hex):
    print (int(hex,16)) # bfn hex string to intege
    print (bin(int(hex,16))) # integer to binary string "return 0b...."
    print (bin(int(hex,16))[2:]) # get rid of the leading "0b"
    print (bin(int(hex,16))[2:].zfill(12)) # fill the string to length of 12 bits
    print (bin(int(hex,16))[2:].zfill(12)[3:12]) 

去测试:

test("1")

输出:

1
0b1
1
000000000001
0000000001
>>> hex = "1"
>>> bin(int(hex, 16))
'0b1'
>>> bin(int(hex, 16))[2:]
'1'
>>> bin(int(hex, 16))[2:].zfill(12)
'000000000001'
>>> bin(int(hex, 16))[2:].zfill(12)[2:]
'0000000001'
>>> bin(int(hex, 16))[2:].zfill(12)[2:11]
'000000000'

如您所见,使用2:11的切片作为索引不包括字符号11(字符串中的第12个字符)。 Python的字符串索引没有错误。

如果要在字符串的末尾进行索引,最好的方法是使用空索引作为切片的第二个元素,就像我在倒数第二条语句中所做的那样。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM