本文介绍了字符串格式(%)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,

我的号码是123456789.01而且,我想像这样格式化

" 123 456 789.01"。

这可能是%字符吗?

Hello,
I''ve a float number 123456789.01 and, I''de like to format it like this
"123 456 789.01".
Is this possible with % character?

推荐答案




否,如

但您可以使用''locale''模块代替。


我怀疑还有一个正则表达式可以处理

,但我不想知道它是什么。 ;-)


-Peter



No, as shown by http://docs.python.org/lib/typesseq-strings.html
but you could probably use the ''locale'' module instead.

I suspect there''s also a regular expression that could deal with
that, but I don''t want to know what it is. ;-)

-Peter







以下应该做你想要的,虽然快速添加的commafy_float我可能有点天真:

def commafy(numstring,thousep ="," ):

"""

Commafy给定的数字字符串numstring


默认情况下,千位分隔符是逗号

"""

numlist = list(numstring)

numlist.revers e()

tmp = []

我在范围内(0,len(numlist),3):

tmp.append( " .join(numlist [i:i + 3]))

numlist = thousep.join(tmp)

numlist = list(numlist)

numlist.reverse()

return"" .join(numlist)

def commafy_float(flStr,thousep =", ):

whole,dec = flStr.split("。")

return"。" .join([commafy(whole,thousep = thousep)

,dec])


if __name__ ==" __ main __":


units =" ; 56746781250450"

unitsWithThouSeps = commafy(单位)

print unitsWithThouSeps

aFloatAsString =" 1128058.23"

aFloatAsStringWithThouSeps = commafy_float(aFloatAsString

,thousep =" ")

打印aFloatAsStringWithThouSeps

问候


- Vincent Wehren



The following should do what you want, although the commafy_float I
quickly added is probably a little naive:
def commafy(numstring, thousep=","):
"""
Commafy the given numeric string numstring

By default the thousands separator is a comma
"""
numlist = list(numstring)
numlist.reverse()
tmp = []
for i in range(0, len(numlist), 3):
tmp.append("".join(numlist[i:i+3]))
numlist = thousep.join(tmp)
numlist = list(numlist)
numlist.reverse()
return "".join(numlist)

def commafy_float(flStr, thousep=","):
whole, dec = flStr.split(".")
return ".".join([commafy(whole, thousep=thousep)
, dec])

if __name__ == "__main__":

units = "56746781250450"
unitsWithThouSeps = commafy(units)
print unitsWithThouSeps
aFloatAsString = "1128058.23"
aFloatAsStringWithThouSeps = commafy_float(aFloatAsString
,thousep=" ")
print aFloatAsStringWithThouSeps
Regards

-- Vincent Wehren


这篇关于字符串格式(%)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 02:00