开发者

formatting a string with multiple float values in python

开发者 https://www.devze.com 2023-03-03 14:45 出处:网络
I am trying to truncate some float values contained in the same string but I\'m not quite sure how to proceed.

I am trying to truncate some float values contained in the same string but I'm not quite sure how to proceed.

Currently I am using the Python xml.dom.minidom to write out some xml using Node.toxml(). I have something like:

1.471392 0.740274 0.659904 -0.560021 1.312128 -0.697930 1.557193 5.156295 2.279541 -0.760170 -0.778676 
-4.882018 0.872503 0.553950 4.468880 -0.793693 0.572676 0.521594 -1.535048 -0.736827 -3.014793 12.288257   
5.243127 -0.850610开发者_运维百科 2.382368 2.183009 0.733634 0.669893 -0.658211 -1.229626 6.780756 -0.608808 -0.914032 

But I would like to truncate each float value to 2 decimal places, so the first value would look something like:

1.47 0.74 

where I have not included the other values.

I guess looping back over the entire document and using some function to loop over each string is the way to go? Has anyone done this before or spot an easy solution I am completely missing?

Many Thanks, C


Here is an one-liner:

" ".join([str(round(float(i),2)) for i in data.split(' ')])

where data contains your string of floats. Might not be the most efficient, but it does the job.


>>> '%.2f' % (1.471392,)
'1.47'


def round_2(f):
    return round(f, 2)

>>> map(round_2, [1.3234254, 2.33521453])
[1.32, 2.34]

Functional programming rocks!

By the way, I'm not entirely clear on whether you are operating on a string, or an array of floats, but if it's the former, just split the string into an array of floats first.


I think this is more exact to the question:

pstring= '%.2f %.2f' % (1.471392, 0.740274 )

print(pstring)

output:

1.47 0.70

0

精彩评论

暂无评论...
验证码 换一张
取 消