【发布时间】:2016-12-29 23:02:56
【问题描述】:
我想使用千位分隔符格式化包含小数点和浮点数的字符串。我试过了:
"{:,}".format()
但它不适用于字符串类型的参数!
>>> num_str = "123456.230"
>>> "{:,}".format(num_str)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Cannot specify ',' with 's'.
>>>
用 Google 搜索解决方案,但找不到任何满足我需求的解决方案。
我的示例输入:"123456.0230"
我想要的示例输出是:"123,456.0230"
我自己写的代码如下:
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)
样品 1:
>>> Input a number: 123456.0230
>>> Output String: 123,456.0230
示例 2:
>>> Input a number: 12345.
>>> Output String: 12,345.
工作正常,但有没有比这更好的方法?
【问题讨论】:
标签: python string performance python-3.x