字符串格式(%) [英] String formatting (%)

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

问题描述

您好,

我的号码是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?

推荐答案

Pascal写道:
Pascal wrote:
您好,我有一个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?




否,如 http://docs.python.org/lib/typesseq-strings.html

但您可以使用''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


Pascal,


这是一个函数我有你想做的事。

警告 - 如果花车变得非常大,就会发生故障。


Larry Bates

Syscon,Inc。


def fmt_wspaces(金额):



#此函数将传递给它的数字并用

#格式将其格式化为千位分隔符。



#如果我得零归零(0.00)



如果不是金额:返回''0.00''



#处理负数



如果金额< 0:sign =" - "

else:sign =""



#拆分为分数和整数



whole_part = abs(长(金额))

fractional_part = abs(金额)-whole_part



#转换为字符串



temp ="%i" %whole_part



#将数字转换为列表



digits = list(temp)



#计算填充长度以填写完整的千位并添加

#填充字符(空格)到开头字符串。



padchars = 3-(len(数字)%3)

if padchars!= 3:digits = tuple (padchars * [''''] +数字)

else:digits =元组(数字)



#创建掩码格式化字符串



sections = len(digits)/ 3

mask = sections *" %s%s%s"

if _debug> 2:logf.writelines(" D"," mask =%s"%mask)

outstring = mask%digits



#放下领先的空间并加回标志



outstring = sign + outstring [1:]。lstrip()



#加回小数部分



outstring + ="%。2f" %fractional_part



返回outtring


if __name __ ==" __ main __":


print" ----------测试负浮动------------------------------

sign = -1

invalue = 0L

for j in range(2):

for我在范围(1,10):

invalue = invalue * 10 + i

print fmt_wspaces(float(sign * invalue) - .01)


print" ----------测试正浮点数--------------------------- ---"

sign = 1

invalue = 0L

for j in range(2):

为范围内的i(1,10):

invalue = invalue * 10 + i

print fmt_wspaces(float(sign * invalue)+。01)


" Pascal" < PA *********** @ free.fr>在消息中写道

新闻:e5 ************************** @ posting.google.c om ...
Pascal,

Here is a function that I had that does what you want.
Warning-If the floats get very large it breaks down.

Larry Bates
Syscon, Inc.

def fmt_wspaces(amount):
#
# This function will take the number passed to it and format it with
# spaces as thousands separators.
#
# If I got zero return zero (0.00)
#
if not amount: return ''0.00''
#
# Handle negative numbers
#
if amount < 0: sign="-"
else: sign=""
#
# Split into fractional and whole parts
#
whole_part=abs(long(amount))
fractional_part=abs(amount)-whole_part
#
# Convert to string
#
temp="%i" % whole_part
#
# Convert the digits to a list
#
digits=list(temp)
#
# Calculate the pad length to fill out a complete thousand and add
# the pad characters (space(s)) to the beginning of the string.
#
padchars=3-(len(digits)%3)
if padchars != 3: digits=tuple(padchars*['' '']+digits)
else: digits=tuple(digits)
#
# Create the mask for formatting the string
#
sections=len(digits)/3
mask=sections*" %s%s%s"
if _debug > 2: logf.writelines("D","mask=%s" % mask)
outstring=mask % digits
#
# Drop off the leading space and add back the sign
#
outstring=sign+outstring[1:].lstrip()
#
# Add back the fractional part
#
outstring+="%.2f" % fractional_part
#
return outstring

if __name__=="__main__":

print "----------testing negative floats------------------------------"
sign=-1
invalue=0L
for j in range(2):
for i in range(1,10):
invalue=invalue*10+i
print fmt_wspaces(float(sign*invalue)-.01)

print "----------testing positive floats------------------------------"
sign=1
invalue=0L
for j in range(2):
for i in range(1,10):
invalue=invalue*10+i
print fmt_wspaces(float(sign*invalue)+.01)

"Pascal" <pa***********@free.fr> wrote in message
news:e5**************************@posting.google.c om...
你好,
我的号码是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?



Pascal写道:
你好,我有一个浮点数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?




以下应该做你想要的,虽然快速添加的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


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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆