简体   繁体   中英

Python Substituiting a float only giving whole number

I'm reading into a csv file an extracting a piece of data with the line:

x = float(node[1])

when I print(x), I get the correct value or the exact value found in the cell. eg 153.018848

But when I try to pass x as variable in the following:

print('<node version="0" lon="%d">' %(x)) 

the output will be <node version="0" lon="153"> . Of course I want the value 153.018848.

What have I overlooked?

Thanks in advance.

You've overlooked the fact that %d is for integers . Try %f instead.

You want to replace your %d with %f, problem solved ;)

See: http://docs.python.org/release/2.5.2/lib/typesseq-strings.html

For bonus points, are you aware you can put together long format strings that are still readable using dictionaries? You can read more about it, but the !r option I have used with call the repr () function on the variable, so you know what is inserted will be exactly what you've seen printed in your debugging:

string = """<tagname id=%{idval!r} type=%{tagtype!r} foo=%{bar!r}"""
print string.format( **{'idval':var1, 'tagtype':var2, 'bar':var3})

You're using the wrong format flag. %d is for integers, use %f for floats.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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