Python Substituiting a float only giving whole number - python

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. e.g 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're using the wrong format flag. %d is for integers, use %f for floats.

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})

Related

Python - string with many variables - which one is throwing the error?

i have a string with 60+ Variables inside and sometimes it throws me an Error: 'must be real number, not str'. While i know what the error means, i donĀ“t know which variable produces it.
Is there a reasonable way to find the trouble making variable?
My actual solution is to split the string up in groups and narrow it down until i find it, but thats quite tedious.
string looks like:
s = "%s bla bla %i some more bla %.2f etc." % \
(test_string, \
test_int, \
test_float)
Thanks for any advice or good ideas.
The error message comes from the %f format operator. %s formats a string, and %i formats an integer.
So you only need to check the variables that correspond to that format. In the example, it's test_float.
You can use this to print the types of all the variables that correspond to %f formats:
for i, v in enumerate([var1, var2, var3]):
if not isinstance(v, float):
print(f"{i} {type(v)}")
This will tell you the indexes in the list of the variables that aren't float.

Python string formatting when already "{}" in the string

I would like to know how could I format this string:
"){e<=2}"
This string is inside a function, so I would like to asign the number to a function parameter to change it whenever I want.
I tried:
"){e<={0}}".format(number)
But it is not working,
Could anybody give me some advice?
Thanks in advance
Double the braces which do not correspond to the format placeholder...
"){{e<={0}}}".format(number)
You could also use an f-string, if using Python 3.6 or above.
f"){{e<={number}}}"
An old-school version for this:
"){e<=%d}" % (number)
'){e<=2}'

String formatting with *args

I looked at the following few posts and wasn't quite able to figure out what I want to do.
python - How to format variable number of arguments into a string?
Pass *args to string.format in Python?
What I want to do is simple. Given some array of variable length I want to be able to print all the arguments individually. That is, I want
print('{} {} ...'.format(*arg))
Obviously I won't be able to predict how many {} I will need before hand and I tried len(x)*'{}' which didn't yield what I wanted. If I leave that out then I only get the first argument. What is the way to achieve this?
so why not just:
print(" ".join(map(str,args)))
which does the same thing as {} {} ... in format
Why use a format string at all? print can do this for you:
print(*arg)

Python print skip arguments

I have this dirty short line of code printing a formatted date:
print '%f %d' % math.modf(time.time())
Now the modf method gives back two arguments, so the print function expects both. In the sake of purely doing this, and not the simple alternative of putting the output separately in a variable; is there any existing way of excepting parameters in print or is there any way to call specific argument-indexes?
For example I have 3 arguments in a print:
print '%s %d.%f' % 'Money',19,.99
I want to skip the first String-parameter that is parsed. Is there any way to do this?
This is mainly a want-to-know-if-possible question, no need to give alternative solutions :P.
Not in "old school" string formatting.
But the format method of strings does have this ability.
print "{1}".format ("1","2")
The above will skip the "1" and will only print "2".
I hope you don't mind I gave an alternative despite you not asking for it :)

Python - Writing to a text file using functions?

i wrote a simple function to write into a text file. like this,
def write_func(var):
var = str(var)
myfile.write(var)
a= 5
b= 5
c= a + b
write_func(c)
this will write the output to a desired file.
now, i want the output in another format. say,
write_func("Output is :"+c)
so that the output will have a meaningful name in the file. how do i do it?
and why is that i cant write an integer to a file? i do, int = str(int) before writing to a file?
You can't add/concatenate a string and integer directly.
If you do anything more complicated than "string :"+str(number), I would strongly recommend using string formatting:
write_func('Output is: %i' % (c))
Python is a strongly typed language. This means, among other things, that you cannot concatenate a string and an integer. Therefore you'll have to convert the integer to string before concatenating. This can be done using a format string (as Nick T suggested) or passing the integer to the built in str function (as NullUserException suggested).
Simple, you do:
write_func('Output is' + str(c))
You have to convert c to a string before you can concatenate it with another string. Then you can also take off the:
var = str(var)
From your function.
why is that i cant write an integer to
a file? i do, int = str(int) before
writing to a file?
You can write binary data to a file, but byte representations of numbers aren't really human readable. -2 for example is 0xfffffffe in a 2's complement 32-bit integer. It's even worse when the number is a float: 2.1 is 0x40066666.
If you plan on having a human-readable file, you need to human-readable characters on them. In an ASCII file '0.5' isn't a number (at least not as a computer understands numbers), but instead the characters '0', '.' and '5'. And that's why you need convert your numbers to strings.
From http://docs.python.org/library/stdtypes.html#file.write
file.write(str)
Write a string to the file. There is no return value. Due to buffering,
the string may not actually show up in
the file until the flush() or close()
method is called.
Note how documentation specifies that write's argument must be a string.
So you should create a string yourself before passing it to file.write().

Categories

Resources