Anomaly in print statement in python [duplicate] - python

This question already has answers here:
How can I selectively escape percent (%) in Python strings?
(6 answers)
Closed 6 years ago.
Suppose I have a print statement in python as given :
print "components required to explain 50% variance : %d" % (count)
This statement gives a ValuError, but if I have this print statement :
print "components required to explain 50% variance"
Why does this happen ?

The error message is pretty helpful here:
>>> count = 10
>>> print "components required to explain 50% variance : %d" % (count)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: unsupported format character 'v' (0x76) at index 35
So python sees % v and it thinks that it is a format code. However, v isn't a supported format character so it raises an error.
The fix is obvious once you know it -- You need to escape the %s that aren't part of a format code. How do you do that? By adding another %:
>>> print "components required to explain 50%% variance : %d" % (count)
components required to explain 50% variance : 10
Note that you could also use .format which is more convenient and powerful in a lot of circumstances:
>>> print "components required to explain 50% variance : {:d}".format(count)
components required to explain 50% variance : 10

The % operator, applied to strings, performs a substitution for every '%' in the string. '50%' does not specify a valid substitution; to simply include a percent sign in the string, you have to double it.

Related

Why won't less-than operator work between these two strings? [duplicate]

This question already has answers here:
Ordering of string representations of integers [duplicate]
(6 answers)
Closed 2 years ago.
Here's my code, super new to python. Struggling to understand why if I use < it always thinks is less than even though it will print a higher number. If I use greater than it works just fine. What am I missing? Here's my code, super new to python. Struggling to understand why if I use < it always thinks is less than even though it will print a higher number. If I use greater than it works just fine. What am I missing?
import time
t=time.localtime()
msttime=time.strftime("%H",t)
if(msttime < '2'):
print(msttime)
else:
print("This calculation believes msttime is greater than 2")
This code will give you the expected result:
import time
t = time.localtime()
msttime = time.strftime("%H", t)
if (int(msttime) < 2):
print(msttime)
else:
print("This calculation believes msttime is greater than 2")
The reason is that "18" < "2" lexographically, but 18 > 2 numerically. This is because the lexographical comparison has no regard for the second digit. Since 1 is before 2, the comparison ends there. In the numerical comparison, all digits are accounted for.

What is the string format "%g%%" mean in python 3? [duplicate]

This question already has answers here:
How can I selectively escape percent (%) in Python strings?
(6 answers)
Closed 4 years ago.
According to python 3 document, the string formating "%%" means "a perncet sign".
Following code is an example:
"%g%%" % 10.34 == "10.34%"
I am not sure what does this "%g" mean here, I suspect it should have the same meaning
as "%g" in string formating, which is "Shorter one among %f or %e". and "%f" or "%e" means
"floating point real number" or "Exponential notaion, lowercase'e'".
Example of them are:
"%f" % 10.34 == '10.34000'
or
"%e" % 1000 == '1.000000e+03'
Based on this understanding, I tried follwoing code. I treid to formatting x first,
and then directly use formating string "%%", but it does not work.
x = '%g' % 10.34
print(isinstance(x, float)) #this returns false
"%%" % x == "10.34%" # this returns error
I then tried this:
x = float(10.34)
print(isinstance(x, float)) #this returns true
"%%" % x == "10.34%" # this returns error as well
I even tried this:
x = "10.34000"
"%%" % x == "10.34%" # this returns error as well
Anyone know what is going on here with "%%". What its mean, do we have to use "%g%%" together with "%%" in any circumstance?
This is solved, the question comes from the misleading of the book. I made comments here:
Since % introduces a format, there must be some way to specify a literal %; that way is %%.
>>> print("%s%%" % "foo")
foo%
It's analogous to how \\ specifies a literal backslash in a string.

Meanings of percent sign(%) [duplicate]

This question already has answers here:
What does % do to strings in Python?
(4 answers)
Closed 8 years ago.
Can you explain what this python code means.
for v in m.getVars():
print('%s %g' % (v.varName, v.x))
The output for the print is
x 3
y 5
The '3' and '5' are values of '(v.varName, v.x)' I don't get how it knows to print 'x' and 'y' and what other uses are there for '%' other than finding the remainder.
The command
for v in m.getVars():
Assigns the list of all Var objects in model m to variable v.
You can then query various attributes of the individual variables in the list.
For example, to obtain the variable name and solution value for the first variable in list v, you would issue the following command
print v.varName, v.x
You can type help(v) to get a list of all methods on a Var object
As others mentioned % is just place holders
To understand how your code works, inspect the model m
It is a way to simplify strings when contain many variables. In python, as you see, you made a string in your print statement which reflects the variables v.varName and v.x. When a percent sign is used in a string, it will be matched, in order, with the parameters you give it.
There are specific letters used for each TYPE of variable. In your case you used "s" and "g" representing a string and a number. Of course numbers are turned into strings if you are creating a string (like in this case).
Example:
x = 20
y = "hello"
z = "some guy"
resulting_string = "%s, my name is %s. I am %g years old" % (y, z, x)
print resulting_string
The result will be:
hello, my name is some guy. I am 20 years old
Notice that the order in the variables section is what gives the correct ordering.

Division in python. 7/9 = 0? How to stop this? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how can I force division to be floating point in Python?
I'm very sorry if this question has been asked already.
timothy_lewis_three_pointers_attempted = 4
timothy_lewis_three_pointers_made = 2
print 'three pointers attempted: ' + str(timothy_lewis_three_pointers_attempted)
print 'three pointers made: ' + str(timothy_lewis_three_pointers_made)
print 'three point percentage: ' + str(timothy_lewis_three_point_percentage)
I'm getting 0 for the percentage. How do I get it to say .5? I know that if I type the numbers as 4.0 and 2.0, I'll get the desired result, but is there another way of doing it?
The other option you have (although I don't recommend it) is to use
from __future__ import division
and then
>>> 7 / 9
0.7777777777777778
This is based on PEP 238.
Make one of them a float:
float(timothy_lewis_three_pointers_made) / timothy_lewis_three_pointers_attempted
You are doing integer division. Make at least one of them a float value
percentage = float(_made) / float(_attempted)
You can also get nicer looking output for percentages by using the new string format method.
"Three point percentage: {:.2%}".format(7.0/9)
# OUT: ' Three point percentage: 77.78%'

The % function in Python [duplicate]

This question already has answers here:
What is the result of % in Python?
(20 answers)
Closed 9 years ago.
I'm working on the exercises in Learning Python the Hard Way and I am wondering what the % function does. I am getting the wrong answer when i count my eggs and hoping understanding this will help me understand what I'm doing wrong.
I can't really tell why your code is broken because you haven't shown anybody what your code is. Please post samples and links next time.
Python % is used in two places, one is mathematical (the modulo operator), and the other has to do with formatting text. I'm going to assume "counting eggs" means the math way.
The modulo operator in X % Y means "Divide X by Y and give me the remainder." So:
10 % 2 == 0
10 % 3 == 1
10 % 11 == 10
That is the the modulo operator

Categories