【问题标题】:Why does checking an empty string against string.hexdigits() return valid?为什么根据 string.hexdigits() 检查空字符串返回有效?
【发布时间】:2016-05-16 05:02:29
【问题描述】:

我有两个函数,一个是清理输入文本,另一个是测试 cleantext 是否为十六进制。当向清理函数传递一个包含所有空格的字符串时,它会去除空格,留下一个空字符串。

我不明白为什么 string.hexdigits() 不会在这个空字符串上出错,让我们作为有效的十六进制传递。

def testHex(ciphertext):
    cleancipher = cleanHex(ciphertext)
    if all(h in string.hexdigits for h in cleancipher):
        print('String is valid hex.')
    else:
        print('String is not valid hex.')

def cleanHex(ciphertext):
    return(ciphertext.replace(' ', '').replace('0x', '').replace(':', '').replace('\\x', '').strip())

【问题讨论】:

  • why string.hexdigits() doesn't barf - 实际上确实如此...string.hexdigits 是一个字符串,您无法调用它并尝试出错。
  • 人们对 SO 投反对票是残酷的,即使这不在搜索范围内。现在结束问题。 编辑: 没有意识到我无法删除答案。我猜只是继续对我投反对票。感谢社区。​​span>
  • @StefanPochmann 我希望它不是一个十六进制数字,而不是一个字符串。提交的答案为我清除了它。
  • 你刚才说的没有有道理。
  • @StefanPochmann 非常感谢您的帮助。

标签: python string python-2.7 hex


【解决方案1】:

testHex 为空字符串输出String is valid hex.,因为all 为空的可迭代对象返回True

documented

所有(可迭代)

如果迭代的所有元素都为真(或者如果 可迭代为空)。

【讨论】:

  • 谢谢,我忙于解析 string.hexdigits() 文档,没想到要检查 all()。当定时器在 10 分钟内到期时,我会接受。
猜你喜欢
  • 1970-01-01
  • 2014-09-25
  • 1970-01-01
  • 1970-01-01
  • 2015-02-20
  • 2018-06-29
  • 2014-04-17
  • 2020-08-27
  • 2016-11-23
相关资源
最近更新 更多