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.
Related
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.
This question already has answers here:
How to display a float with two decimal places?
(13 answers)
Closed 6 years ago.
x="1,234.00"
y =x.replace(',','')
k = float(y)
print k
output=1234.0 but i need 1234.00 value
please solve this problem
There is no difference in value between 1234.0 and 1234.00. You can't save more or less non-significant digits in a float.
However, you can print more or less (non-)significant digits. In older versions of python you can use the % method (documentation). In Python 2.7 and up, use the string format method. An example:
f = float('156.2')
# in Python 2.3
no_decimals = "%.0f" % f
print no_decimals # "156" (no decimal numbers)
five_decimals = "%.5f" % f
print five_decimals # "156.20000" (5 decimal numbers)
# in Python 2.7
no_decimals = "{:.0f}".format(f)
print no_decimals # "156" (no decimal numbers)
five_decimals = "{:.5f}".format(f)
print five_decimals # "156.20000" (5 decimal numbers)
If you for some reason have no access to the code that prints the value, you can create your own class, inherit from float and supply your own __str__ value. This could break some behaviour (it shouldn't, but it could), so be careful. Here is an example:
class my_float(float):
def __str__(self):
return "%.2f" % self
f = my_float(1234.0)
print f # "1234.00"
(I ran this on Python 2.7, I have 2.3 not installed; please consider upgrading Python to 2.7 or 3.5; 2.3 is seriously outdated.)
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.
This question already has answers here:
Display number with leading zeros [duplicate]
(19 answers)
Closed 6 months ago.
In Python, how do I specify a format when converting int to string?
More precisely, I want my format to add leading zeros to have a string
with constant length. For example, if the constant length is set to 4:
1 would be converted into "0001"
12 would be converted into "0012"
165 would be converted into "0165"
I have no constraint on the behaviour when the integer is greater than what can allow the given length (9999 in my example).
How can I do that in Python?
"%04d" where the 4 is the constant length will do what you described.
You can read about string formatting here.
Update for Python 3:
{:04d} is the equivalent for strings using the str.format method or format builtin function. See the format specification mini-language documentation.
You could use the zfill function of str class. Like so -
>>> str(165).zfill(4)
'0165'
One could also do %04d etc. like the others have suggested. But I thought this is more pythonic way of doing this...
With python3 format and the new 3.6 f"" notation:
>>> i = 5
>>> "{:4n}".format(i)
' 5'
>>> "{:04n}".format(i)
'0005'
>>> f"{i:4n}"
' 5'
>>> f"{i:04n}"
'0005'
Try formatted string printing:
print "%04d" % 1 Outputs 0001
Use the percentage (%) operator:
>>> number = 1
>>> print("%04d") % number
0001
>>> number = 342
>>> print("%04d") % number
0342
Documentation is over here
The advantage in using % instead of zfill() is that you parse values into a string in a more legible way:
>>> number = 99
>>> print("My number is %04d to which I can add 1 and get %04d") % (number, number+1)
My number is 0099 to which I can add 1 and get 0100
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
how to parse hex or decimal int in Python
i have a bunch of Hexadecimal colors in a database stored as strings.
e.g. '0xFFFF00'
when i get them from the database i need to convert this string into an actual hexadecimal number, so
0xFFFF00
how can i do this in python
This is one way to do it:
>>> s = '0xFFFF00'
>>> i = int(s, 16)
>>> print i
hex(int('0xFFFF00', 16))
Also this works
number = int('0xFFFF00',0)
print("%x follows %x" % (number+1, number))
0 argument tells interpreter to follow the Python rules of numbers to decide the used format of number so this expression will work right for all numbers.