Python 布尔值到小写字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25361293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Boolean to string with lowercase
提问by tubafranz
Can the str.format()method print boolean arguments without capitalized strings?
该str.format()方法可以打印没有大写字符串的布尔参数吗?
I cannot use str(myVar).lower()as argument of format, because I want to preserve the case of the letters when myVaris not a boolean.
我不能str(myVar).lower()用作格式参数,因为我想在myVar不是布尔值时保留字母的大小写。
Please don't post solutions with conditional checks of the values of the variable.
请不要发布带有条件检查变量值的解决方案。
All I am interested is in the possibility of writing the following:
我所感兴趣的是编写以下内容的可能性:
"Bla bla bla {}".format(myVar)
so that the output becomes "Bla bla bla true"when myVar == Trueand "Bla bla bla false"when myVar == false
使得输出变为"Bla bla bla true"时myVar == True和"Bla bla bla false"当myVar == false
回答by John La Rooy
You could use an expression like this
你可以使用这样的表达
str(myVar).lower() if type(myVar) is bool else myVar
回答by Burhan Khalid
Try a lambda that you can call:
尝试一个可以调用的 lambda:
>>> f = lambda x: str(x).lower() if isinstance(x, bool) else x
>>> 'foo {} {}'.format(f(True), f('HELLO'))
'foo true HELLO'

