【问题标题】:Boolean to string with lowercase布尔值转为小写字符串
【发布时间】:2014-10-11 05:56:42
【问题描述】:

str.format() 方法可以打印不带大写字符串的布尔参数吗?

我不能使用str(myVar).lower() 作为格式参数,因为我想在myVar 不是布尔值时保留字母的大小写。

请不要发布对变量值进行条件检查的解决方案。

我感兴趣的只是写以下内容的可能性:

"Bla bla bla {}".format(myVar)

这样当myVar == True"Bla bla bla false"myVar == false 时输出变成"Bla bla bla true"myVar == false

【问题讨论】:

  • 你想要小写布尔值有什么特别的原因吗?例如,这是JSON 相关的吗?
  • 不,str.format() 不会转换布尔值的大小写;您需要手动执行此操作。为什么需要这个?
  • if mybool: str = 'true' else: str = 'false'
  • @Unihedron:boolval = 'true' if mybool else 'false'。或者只是str(mybool).lower()..
  • "ftarlusee"[myVar::2] 获得更多乐趣 :)

标签: python string format boolean lowercase


【解决方案1】:

你可以使用这样的表达式

str(myVar).lower() if type(myVar) is bool else myVar

【讨论】:

  • isinstance(myVar, bool) 是首选,即使 bool 不能被进一步子类化。
【解决方案2】:

尝试一个可以调用的 lambda:

>>> f = lambda x: str(x).lower() if isinstance(x, bool) else  x
>>> 'foo {} {}'.format(f(True), f('HELLO'))
'foo true HELLO'

【讨论】:

猜你喜欢
  • 2018-09-07
  • 1970-01-01
  • 2011-11-12
  • 2013-01-24
  • 2021-05-07
  • 2012-03-10
  • 2012-12-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多