2012-09-20 122 views
0

我有一堆字符串格式的數字,我想在函數的一些想法來格式化這些。python字符串格式化函數

ex。

輸入00000000.00 - 應該輸出0.00

輸入00000123.00 - 應該輸出123.00

輸入0000-123.00 - 應該輸出-123.00

輸入00-00123.45 - 應該輸出-123.45

input -0000123.00 - should output -123.00

input 00000000.-5 - should output -0.05

輸入0000000 -0.25 - 應該輸出-0.25

一個soultion,我能想到的含負號的字符串是如下 前。 NUM =「0000-123.00」

if num.find("-") != -1: 

    num = "-" + num.replace("-","") 

這會給我NUM爲-0000123.00,但我不知道如何擺脫前導零的。

回答

0

您可以分析,像這樣的數字:

然後使用Python的字符串格式化格式化,

num = "{:0.2f}".format(parse_funky_numstring(s)) 
+0

完美 - 感謝 – wadapav

+0

如果不是第六輸入例如一個可以簡單地做'float(s.lstrip('0'))'。 @wadapav如果這個答案好,你應該接受它。 – Bakuriu