[英]Properly printing a character depending on a variable using python
I'd like to know if there was a good pythonic way to do something like this: 我想知道是否有一种很好的pythonic方式来做这样的事情:
size1 = 4
size2 = 3
value = size1 - size2
def isSign(value):
if value > 0 :
return "+"
else :
return ""
print("My total gain is" + isSign(value) + str(value))
In this case my string should look like this: 在这种情况下,我的字符串应如下所示:
My total gain is +1
In a case where value is -1 my string should look like this: 在value为-1的情况下,我的字符串应如下所示:
My total gain is -1
In a case where value is 0 my string should look like this: 在value为0的情况下,我的字符串应如下所示:
My total gain is 0
I'd also like to avoid extern modules if possible. 如果可能的话,我也想避免使用外部模块。
You can replace isSign(value)
with (value > 0) * "+"
. 您可以将isSign(value)
替换为(value > 0) * "+"
。
This works because True == 1
and False == 0
, and a number n
times a string is that string repeated n
times, so 0 * "+"
is the empty string ""
. 这工作,因为True == 1
和False == 0
,和一些n
次字符串是该字符串重复n
倍,所以0 * "+"
是空字符串""
。
However, some may find it unreadable, as evidenced by the fact that I have to explain how it works. 但是,有些人可能觉得它不可读,我必须解释它是如何工作的事实证明了这一点。
Using an f-string: 使用f字符串:
f"My total gain is {(value > 0) * '+'}{value}"
f字符串是执行此操作的好方法:
print(f'My total gain is {"+" if value > 0 else ""}{value}')
String formatting provides a +
flag for this: 字符串格式为此提供了一个+
标志:
>>> "{:+}".format(3)
'+3'
>>> "{:+}".format(-3)
'-3'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.