如何打印标志 + Python 中正数的数字

发布于 2024-08-31 17:17:35 字数 199 浏览 1 评论 0原文

有没有更好的方法在正数上打印数字的+号?

integer1 = 10
integer2 = 5
sign = ''
total = integer1-integer2
if total > 0: sign = '+'
print 'Total:'+sign+str(total)

0 应该返回 0,不带 +。

Is there a better way to print the + sign of a digit on positive numbers?

integer1 = 10
integer2 = 5
sign = ''
total = integer1-integer2
if total > 0: sign = '+'
print 'Total:'+sign+str(total)

0 should return 0 without +.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

咋地 2024-09-07 17:17:35

使用新字符串格式

>>> '{0:+} number'.format(1)
'+1 number'
>>> '{0:+} number'.format(-1)
'-1 number'
>>> '{0:+} number'.format(-37)
'-37 number'
>>> '{0:+} number'.format(37)
'+37 number'
# As the questions ask for it, little trick for not printing it on 0
>>> number = 1
>>> '{0:{1}} number'.format(number, '+' if number else '')
'+1 number'
>>> number = 0
>>> '{0:{1}} number'.format(number, '+' if number else '')
'0 number'

建议 而不是%操作员

Use the new string format

>>> '{0:+} number'.format(1)
'+1 number'
>>> '{0:+} number'.format(-1)
'-1 number'
>>> '{0:+} number'.format(-37)
'-37 number'
>>> '{0:+} number'.format(37)
'+37 number'
# As the questions ask for it, little trick for not printing it on 0
>>> number = 1
>>> '{0:{1}} number'.format(number, '+' if number else '')
'+1 number'
>>> number = 0
>>> '{0:{1}} number'.format(number, '+' if number else '')
'0 number'

It's recommended over the % operator

小红帽 2024-09-07 17:17:35
>>> print "%+d" % (-1)
-1
>>>
>>> print "%+d" % (1)
+1
>>> print "%+d" % (0)
+0
>>>

这是文档

**更新** 如果出于某种原因您无法使用 % 运算符,则不需要函数:

>>> total = -10; print "Total:" + ["", "+"][total > 0] + str(total)
Total:-10
>>> total = 0; print "Total:" + ["", "+"][total > 0] + str(total)
Total:0
>>> total = 10; print "Total:" + ["", "+"][total > 0] + str(total)
Total:+10
>>>
>>> print "%+d" % (-1)
-1
>>>
>>> print "%+d" % (1)
+1
>>> print "%+d" % (0)
+0
>>>

Here is the documentation.

** Update** If for whatever reason you can't use the % operator, you don't need a function:

>>> total = -10; print "Total:" + ["", "+"][total > 0] + str(total)
Total:-10
>>> total = 0; print "Total:" + ["", "+"][total > 0] + str(total)
Total:0
>>> total = 10; print "Total:" + ["", "+"][total > 0] + str(total)
Total:+10
>>>
ㄖ落Θ余辉 2024-09-07 17:17:35

从 python 3.6 开始:

>>> integer1 = 10
>>> integer2 = 5
>>> total = integer1-integer2
>>> print(f'Total: {total:+}')
Total: +5

或:

for i in range(-1,2):
    print (f' {i} becomes {i:+}')

输出:

 -1 becomes -1
 0 becomes +0
 1 becomes +1

From python 3.6 onwards:

>>> integer1 = 10
>>> integer2 = 5
>>> total = integer1-integer2
>>> print(f'Total: {total:+}')
Total: +5

or:

for i in range(-1,2):
    print (f' {i} becomes {i:+}')

outputs:

 -1 becomes -1
 0 becomes +0
 1 becomes +1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文