在我的场景(python 2.7)中,我有:
str(var)
其中var是一个变量,有时需要数千个分隔符,例如1,500,但正如您所看到的那样,已转换为字符串(用于连接目的).
我希望能够将该变量打印为具有数千个分隔符的字符串.
我已经阅读了为数字添加格式的解决方案,例如:
>>> '{:20,.2}'.format(f)
'18,446,744,073,709,551,616.00'
Run Code Online (Sandbox Code Playgroud)
但这似乎仅适用于数字,而不适用于已转换为字符串的数字.
谢谢.
编辑: 对于更具体的上下文,这是我的实现场景:
print 'the cost = $' + str(var1) + '\n'
print 'the cost = $' + str(var2) + '\n'
Run Code Online (Sandbox Code Playgroud)
我有几个'vars'.
我是一个新手学习python(2.7.3),并给了一个简单的练习计算成本,但很快就开始对真正能够控制或理解正在生成的结果的"正确性"感兴趣.如果我在我的计算机上使用计算器我得到的结果我认为我在追求(即它们看起来非常具体),但如果我使用python似乎我必须非常准确地说我如何将格式信息添加到正在使用的值和打印.
我的问题的简短版本是:
是否有一个简单的解决方案,我可以使用每当我使用返回的货币时:
如果有人想要运行它以查看结果和变化,我一直在使用解释器(见下面的代码)来测试变化.
谢谢.
# basic entry - both are seen as integers
print 'A: ', 7/3
# test by printing out the types
print 'B: ', type(7)
print 'C: ', type(3)
# this is not necessary as they are already integers
print 'D: ', int(7/3)
# converts the result of 7/3 into a floating number
print 'E: ', float(7/3)
# defines the float version of 7 by the float version of 3
print 'F: ', …Run Code Online (Sandbox Code Playgroud) 我想更改千位分隔符,以便{:,}.format(1234)在Python中使用不同的字符.分隔符应该是'\u066c'.
如何在不影响任何其他本地设置的情况下设置此项?
编辑:欢迎使用固定字体的任何其他建议的无效分隔符!
我已经看到很多问题教导如何使用comma千位分隔符来做到这一点:
>>> format(1123000,',d')
'1,123,000'
Run Code Online (Sandbox Code Playgroud)
但如果我尝试使用 a dot,它就会变得疯狂:
>>> format(1123000,'.d')
ValueError: Format specifier missing precision
Run Code Online (Sandbox Code Playgroud)
是否有一种简单的Python内置独立于区域设置的方法可以使其输出'1.123.000'而不是输出'1,123,000'?
我已经在“将‘小数点’千位分隔符添加到数字”
上找到了这个答案,但它是手动执行的。它可以更简单,因为format(1123000,'.d')与语言环境无关吗?或者Python没有内置它?
@Eugene Yamash使用
itertools可以给你更多的灵活性:Run Code Online (Sandbox Code Playgroud)>>> from itertools import zip_longest >>> num = "1000000" >>> sep = "." >>> places = 3 >>> args = [iter(num[::-1])] * places >>> sep.join("".join(x) for x in zip_longest(*args, fillvalue=""))[::-1] '1.000.000'
假设我有一个pandas数据框,并且想对所有数字(整数和浮点数)添加千位分隔符,那么有什么简便快捷的方法呢?
我有一个以名称为索引的系列和一个以科学记数法表示的数字,例如 3.176154e+08。如何使用千位分隔符将此数字转换为 317,615,384.61538464?我试过:
格式(s, ',')
但它返回 TypeError: non-empty format string传递给对象。format 数据中没有 NaN。
谢谢你的帮助!
python ×6
pandas ×2
python-2.7 ×2
python-3.x ×2
arabic ×1
format ×1
formatting ×1
locale ×1
separator ×1