简体   繁体   English

在 python 中格式化具有多个浮点值的字符串

[英]formatting a string with multiple float values in python

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().目前我正在使用 Python xml.dom.minidom 使用 Node.toxml() 写出一些 xml。 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?我想循环遍历整个文档并使用一些 function 循环遍历每个字符串是通往 go 的方法吗? Has anyone done this before or spot an easy solution I am completely missing?以前有没有人这样做过或发现了一个我完全想念的简单解决方案?

Many Thanks, C非常感谢,C

Here is an one-liner:这是一个单行:

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

where data contains your string of floats.其中 data 包含您的浮点数字符串。 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 ) pstring= '%.2f %.2f' % (1.471392, 0.740274 )

print(pstring)打印(字符串)

output: output:

1.47 0.70 1.47 0.70

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

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