简体   繁体   English

字符串类型变量的自定义千位分隔符

[英]Customized thousand separator for string type variable

I want to format my string containing both decimal and floating point using thousand separator. 我想使用千位分隔符来格式化包含小数点和浮点数的字符串。 I've tried: 我试过了:

"{:,}".format() 

but it is not working with an argument of string type! 但是它不适用于字符串类型的参数!

>>> num_str = "123456.230"
>>> "{:,}".format(num_str)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Cannot specify ',' with 's'.
>>>

Googled for solution(s) but couldn't find any solution(s) that satisfy my needs. 搜索了解决方案,但找不到满足我需求的任何解决方案。

My sample input: "123456.0230" 我的样本输入: "123456.0230"

My desired sample output to be: "123,456.0230" 我希望的样本输出为: "123,456.0230"

I wrote my own code which is as follows: 我编写了自己的代码,如下所示:

input_str = ''
output_str = ''
lenth = 0

input_str = input("Input a number: ")

for i in input_str:
    if input_str[lenth] == '.':
        break
    lenth += 1

if lenth % 3 == 0:
    pos_separator = 3
else:
    pos_separator = lenth % 3

for i in range(0, lenth):
    if i == pos_separator:
        output_str += ',' + input_str[i]
        pos_separator += 3
    else:
        output_str += input_str[i]

output_str += input_str[lenth:]

print("Output String: ", output_str)

Sampe 1: Sampe 1:

>>> Input a number: 123456.0230
>>> Output String:  123,456.0230

Sample 2: 范例2:

>>> Input a number: 12345.
>>> Output String:  12,345.

Working okay but is there any other way better than this? 可以,但是还有其他更好的方法吗?

You can just make it a float and then apply it: 可以将其设置为浮动, 然后将其应用:

>>> "{:,}".format(float(num_str))
'123,456.23'

>>> "{:,}".format(float(12345))
'12,345.0'

You can also utilize the 'g' specifier to remove trailing zeros if required: 如果需要,您还可以利用'g'说明符删除尾随零:

>>> "{:,g}".format(float(12345))
'12,345'

As pointed out by @ user2357112 in a comment, you optimally could import Decimal and feed that into .format instead: 正如@ user2357112在评论中指出的那样,您可以最佳地导入Decimal并将其提供给.format

>>> from decimal import Decimal
>>> "{:,}".format(Decimal(num_str))
'123,456.230'

Since you also have cases as the trailing dot, where it needs to be preserved and since I cannot think of a way .format can do this on its own, create a little function that will append '.' 由于您还需要将.format作为尾随点,因此需要保留它,并且由于我无法想到.format可以自行完成此操作的方式,因此请创建一个附加'.'的小函数'.' if it exists and do nothing if it doesn't: 如果存在,则不执行任何操作:

def format_str(s):
    fstr = "{:,}".format(Decimal(s))
    return fstr + ('.' if s[-1] == '.' else '')

Which, for some test cases: 对于一些测试用例:

for s in ['12345', '12345.', '1234.5']:
    print(format_str(s))

yields: 收益率:

12,345
12,345.
1,234.5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM