【问题标题】:Why is the dictionary element returning 1 as far as length when the String at that location should return 9?当该位置的字符串应返回 9 时,为什么字典元素返回 1 的长度?
【发布时间】:2021-04-21 18:35:48
【问题描述】:

所以我试图做一些从字符串中减去一定数量的东西,以使 2 个字符串的长度相等,问题是当我尝试找到存储为 0000 0000 的元素 1 的长度时,它返回 1。此外,代码是从文件中获取的,但唯一相关的元素是 1。这是有问题的代码:

import re

insSpec2 = {}
z = 0
bool(z)
TestString = "0100 0001"

while z == 0:
    f = open("Specifier", 'r')

    for word in f:
        i = 0
        insSpec2[i] = re.split('r|a', word)
        print(insSpec2[i])

        insLength = len(insSpec2[i])
        testLength = len(TestString)
        if testLength > insLength:
            diff = testLength-insLength
        else:
            diff = insLength-testLength

        print(insLength)#returns 1
        print(testLength, insLength) #returns 9 1
        print(diff)#returns 8
        print(insSpec2[0].__len__()) #returns 1

        if insLength < testLength:
            changeVar = 8 - insLength
            while TestString != insSpec2:
                #print(testLength)
                newStr = TestString[:-diff]
                #print(newStr)
        elif insSpec2[i] == TestString:
            print("Found Match", insSpec2[i])
            z = 1
            break

        i += 1

【问题讨论】:

    标签: python string dictionary comparison string-comparison


    【解决方案1】:

    那是因为re.split 返回一个列表而不是字符串,insSpec[i] = ['0000 0000']。它的长度为 1

    【讨论】:

    • 那么我怎样才能得到它来获取字符串长度呢?
    • insSpec[i] 包含正则表达式拆分的结果。所以如果字符串实际上没有被分割,字符串长度是len(insSpec[i][0])。如果有,则此表达式返回第一个子字符串的长度。
    猜你喜欢
    • 2015-04-01
    • 2016-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-29
    • 1970-01-01
    • 2020-09-19
    • 1970-01-01
    相关资源
    最近更新 更多