简体   繁体   English

Python字符串索引错误?

[英]Python string indexing bug?

I ran into an interesting behavior in Python string indexing and I think might be a bug. 我在Python字符串索引中遇到了一个有趣的行为,我认为这可能是一个错误。

The purpose of my code is to perform a series of manipulation to turn a hex string into binary (12 bits) and take a subset (10 LSB) of the binary string 我的代码的目的是执行一系列操作,以将十六进制字符串转换为二进制(12位)并获取二进制字符串的子集(10 LSB)

The code that gives the result I expect looks like this: 提供我期望的结果的代码如下所示:

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

if input "1", ie hex = "1" 如果输入“ 1”,即十六进制=“ 1”

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

bin(int(hex,16))[2:] gets rid of the leading 0b and returns 1 -- works as expected [2:] give the 3rd char and onwords bin(int(hex,16))[2:]删除前导0b并返回1按预期工作[2:]给出第三个字符和onwords

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

now comes the interesting part, in order to get the 10 LSB, ie the 3rd to 12th char one would use 现在出现了有趣的部分,为了获得10 LSB,即一个人将使用的第3至第12个字符

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

however, it seems I had to use bin(int(hex,16))[2:].zfill(12)[3,12] to get 00_0000_0001 , which seems to suggest that somehow the indexing became 1 based instead of 0 based after the .zfill(12) ? 但是,似乎我不得不使用bin(int(hex,16))[2:].zfill(12)[3,12]来获取00_0000_0001 ,这似乎表明索引以某种方式变为基于1而不是基于0.zfill(12)

The results is obtained with Python 3.4.1 结果是使用Python 3.4.1获得的

Any suggestion is appreciated! 任何建议表示赞赏!

Here is the test code: 这是测试代码:

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]) 

to test: 去测试:

test("1")

output: 输出:

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'

As you can see, using a slice of 2:11 as an index does not include character number 11 (the 12th character in the string). 如您所见,使用2:11的切片作为索引不包括字符号11(字符串中的第12个字符)。 There is no bug in Python's string indexing. Python的字符串索引没有错误。

If you want to index right up the the end of the string the best way to do that is to use an empty index as the second element of the slice, as I did in the second-to-last statement above. 如果要在字符串的末尾进行索引,最好的方法是使用空索引作为切片的第二个元素,就像我在倒数第二条语句中所做的那样。

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

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