![](/img/trans.png)
[英]How to print +1 in Python, as +1 (with plus sign) instead of 1?
[英]How to add a plus sign before an int in Python?
我需要以非常特定的格式生成输出,并且正整数必须在它们前面带有加号。 我正在使用numpy数组,并正在尝试类似的东西:
if(int(P[pnt])>0):
P[pnt] += np.insert(P[pnt-1],0,"+")
但是,它永远不会将加号添加为数字的一部分,而是添加为其他实例。
我也尝试将其保存在其他文件中,然后从那里进行修改(使用re.sub()
等...),但是没有运气:(
我的输出看起来像这样:
(+1 2 -4 +5 -3)
(+1 2 3 -5 4)
(+1 2 3 -4 5)
(+1 2 3 4 5)
并应如下所示:
(+1 +2 -4 +5 -3)
(+1 +2 +3 -5 +4)
(+1 +2 +3 -4 +5)
(+1 +2 +3 +4 +5)
如果需要,我可以共享整个代码...
谢谢!! :)
使用.format()
和Python Format迷你语言 。 您需要+
符号选项。
'{:+}'.format(3) # "+3"
'{:+}'.format(-3) # "-3"
可能会发疯:
a = numpy.array([1, 2, -4, 5, -3])
print '(' + ' '.join('{:+}'.format(n) for n in a)) + ')'
# (+1 +2 -4 +5 -3)
加上尼克T的答案:
您可以编辑numpy的打印选项,因此每当您打印numpy数组时,都会进行格式化。
In [191]: np.set_printoptions(formatter={'all':lambda x: '{:+}'.format(x)})
In [198]: np.random.random_integers(-5,5,(5,5))
Out[198]:
array([[+2, +2, +2, -4, +0],
[-2, -1, +3, +5, -1],
[-5, -2, -1, -3, +4],
[+1, +3, -5, +3, -4],
[+2, -1, +2, +5, +5]])
'all'
定义了此格式应使用的类型。 set_printoptions的文档字符串将告诉您可以在此处设置的内容,以实现更特定的格式。
- 'bool'
- 'int'
- 'timedelta' : a `numpy.timedelta64`
- 'datetime' : a `numpy.datetime64`
- 'float'
- 'longfloat' : 128-bit floats
- 'complexfloat'
- 'longcomplexfloat' : composed of two 128-bit floats
- 'numpy_str' : types `numpy.string_` and `numpy.unicode_`
- 'str' : all other strings
Other keys that can be used to set a group of types at once are::
- 'all' : sets all types
- 'int_kind' : sets 'int'
- 'float_kind' : sets 'float' and 'longfloat'
- 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat'
- 'str_kind' : sets 'str' and 'numpystr'
我不在可以测试它的环境中,但是numpy.insert应该沿轴插入对象,并在选择的对象之前添加新的索引/值。
相反,在您的条件语句中,真实结果可以将P [pnt]设置为等于'+'+ str(P [pnt])。 您正在寻找最后的字符串数组,是吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.