簡體   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