【问题标题】:I have an issue in python code snippet我在 python 代码片段中有一个问题
【发布时间】:2018-03-03 06:53:15
【问题描述】:

如果值中包含双引号,则 python 函数正在完美地读取值,但如果我们根本没有引号,则无法处理相同的值。

def str_to_bool(text):
    if text.lower().strip("\"\' \t\n\r") in ("yes", "y", "true",  "t", "1"):
        return True
    return False

以下部分使用此函数读取值/键

for key in ["systemSDI", "systemOSN"]:
        if (key in facts) and facts[key]:
            provRequest.set(section, key, str(node.str_to_bool(facts[key])))

如果值类似于 systemSDI: "YES" 则此方法有效,但如果 systemSDI: YES 则无效 我希望以这样一种方式调整功能,使其在这两种情况下都可以工作

事实:

operatingsystemrelease: "5.8"
operatingsystem: OEL
system: cacr-TEST
systemLevel: TEST
systemSDI: "YES"
systemOSN: "NO"

【问题讨论】:

  • 如果为真则不需要:返回真否则在str_to_bool中返回假@...
  • 请提供facts,以便我们运行您的代码。
  • 我的意思是,一个真正的代码......因为错误可能存在。

标签: python boolean


【解决方案1】:

代码正确:

>>> str_to_bool("YES")
True
>>> str_to_bool('"YES"')
True

所以,如果它没有按预期工作,请检查您的输入数据。

顺便说一下,你的函数可以转换为:

def str_to_bool(text):
   return text.lower().strip("\"\' \t\n\r") in ("yes", "y", "true",  "t", "1")

【讨论】:

  • 如果该行类似于 systemSDI: YES 它失败,
  • 如果该行类似于 systemSDI:是的,它失败了,Traceback (most recent call last): File "/usr/local/strap/bin/boot_install.py", line 102, in <module> provRequest.set(section, key, str(node.str_to_bool(facts[key]))) File "/usr/local/strap/lib/node.py", line 264, in str_to_bool if text.lower().strip("\"\' \t\n\r") in ("yes", "y", "true", "t", "1"): AttributeError: 'bool' object has no attribute 'lower' bootstrap configuration failed
  • 试试这个:node.str_to_bool(str(facts[key])))
猜你喜欢
  • 1970-01-01
  • 2012-08-04
  • 1970-01-01
  • 1970-01-01
  • 2022-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-13
相关资源
最近更新 更多