Python output formats - python

Hi there I've had a search output formats and formats had no luck. I couldn't find right documentation for it and I really want to learn how this code works if somebody could enlighten me please?
print ("Survived: %i (%.1f%%)"%(len(survived), float(len(survived))/len(train)*100.0))
print ("Not Survived: %i (%.1f%%)"%(len(not_survived), float(len(not_survived))/len(train)*100.0))
print ("Total: %i"%len(train))
My questions is inside the code % symbols %i %.1f%% (I believe one decimal) I just really struggle understanding this code how it works (%%%) wise. if somebody could break down for me.
Output is:
Survived: 342 (38.4%)
Not Survived: 549 (61.6%)
Total: 891
Thank you.

Python supports different ways of formatting strings. Unfortunately, they are not all in the same place in the documentation. So, I guess it makes sense to put them all in one SO answer :)
What you have in the question is printf-style formatting using the modulo (%) operator. For the specification of that see printf-style String Formatting.
Example:
x = 9
print('value of x is %d' % x)
For formatting using the format function, see Format String Syntax.
Example:
x = 9
print('value of x is {x}'.format(x=x))
The same syntax is used as basis for f-strings. See PEP-0498.
Example:
x = 9
print(f'value of x is {x}')
There are also template strings, see Template strings specification.
Example:
x = 9
print(string.Template('value of x is $x').substitute(x=x))

Related

How does '%.*g' % (6,k) work in python

I have the following piece of code: (Python 2.7)
k = 4535.65463456
out = '%.*g' % (6,k)
print str(out)
Output: 4535.65
I am not able to understand the working of '%.*g' % (6,k). Since I not familiar with this syntax and don't know what this is called, I am not even able to google it. Could someone help me with this?
Thanks in advance.
With C-borrowed syntax "%6g" you're able to tell python to display your float with a maximum of six digits (if the number isn't too large).
It means that if the integer part of the number has 4 digits, it will use the 2 remaining digits to print the most significant decimal part.
Now if we want to make it parametrizable, we have to generate the format string, which isn't very convienient, so Python introduced Parametrized precision in such strings.
'%.*g' % (6,k)
prints k with 6 digits max.
Now you'll be better of the "new" formatting using format, which allows "nested" formatting to generate the outer formatting (so no need for intricate .* syntax):
'{:.{prec}g}'.format(k, prec=6) # courtesy of Dan comment
Here prec isn't even a special keyword, just the parameter name passed as a function keyword. This is like:
'{:6g}'.format(k)
There's an entire website dedicated to python old & new style formats: https://pyformat.info/
(and there's also a newer syntax with Python 3.6 format strings... https://www.python.org/dev/peps/pep-0498/)
out = '%.*g' % (6,k)
that mean it will print the nember after ,6 ; look at '%.' %. = 4535. , that will be printed then '.*g' , * = 6 , the number after the ',' then g = 5 then number after 6

Adding two string values that contain integers in Python

Brand new to Python and coding in general. Teaching myself and playing around with various outputs in Python. I was messing around today and tried to compute two what I believe are string values into the defined floating point format.
a = "%.2f" %x + str(float(14.00))
returns '3.3514.0'
a = "%.2f" %x , str(float(14.00))
returns ('3.35, '14.0')
I was able to separate these two values but i was not able to get the proper value of 17.75 computed. I would like to take x (which = 3.3456), round to two decimal places ("%.2f" %x) take the floating value of 14.00 (float(14.00) and add these two together then define that computation with a. so a = x to two decimals + float(14.00).
What am I doing wrong?
-Alfa
try this
a = float("%.2f" %x) + float(14.00)
In the first case you're just trying to concat these two strings. In Python '+' used on strings means 'add the second string on the end of first one', so that's why you're getting ugly result. I would suggest to count values out of the string, next use string formating, but If you must do it, It can be something like:
a = '%.2f' % str(float_value1 + float_value2)`
Better solution is to use .format, as someone mentioned.
is not
a = "%.2f" %x + str(float(14.00))
but
a = ""%.2f" % str(float(14.00))
or better (doc)
'here {} '.format(str(float(14.00)))

Difference in printing in Python

I am learning Python and here is an example of some code :
When would you use this :
Y = "Apple"
print "The object is an %s" % Y
And when would you use this?
X = "Grape"
print "The object is an " , X
And why?
The difference goes beyond just convenience and preference. The two methods are two different things.
Let's consider print "The object is an " , X first. The print statement in Python 2 is a bit irregular and unintuitive in its behavior, which is one of the reasons why Python 3 has a print function instead. In Python 2, the statement takes comma-separated expressions, and prints them out one by one, converting them to strings if necessary, and using a few rules to decide whether to put a space before each expression (it puts a space except "(1) when no characters have yet been written to standard output, (2) when the last character written to standard output is a whitespace character except ' ', or (3) when the last write operation on standard output was not a print statement.")
So when you have strings X and Y, and do print X,Y, it prints X and then Y, probably with whitespace in between. If you want to print a bunch of things quickly, this works well. It's to some extent an easy shorthand for combining separate strings as well. It just prints string representations of the expressions you put in, however. Unless you've already converted the objects to the string you want them to be, you don't have any control over what they look like. It is also something that's specific to the print statement.
The % operation for string formatting, on the other hand, is its own thing; you don't need to use it with print. You can also do things like a = "The object is an %s." % X, and it will work as expected, substituting in the X. But that's not all it can do, or it wouldn't be called string formatting. Instead, it allows you to control how things are put into the string, especially for numbers. This makes it more generally useful, even if the usage is a bit opaque, and reading the documentation on it is a good idea. But, as some examples:
In [1]: a = 1507.2515621
In [2]: print "a is: %d" % a # print as a signed integer
a is: 1507
In [3]: print "a is: %f" % a # print as a float, decimal format
a is: 1507.251562
In [4]: print "a is: %10.2E" % a # print as a float in exponential format, with
a is: 1.51E+03
In [5]: print "a is: %x" % a # signed hexadecimal
a is: 5e3
In [6]: print "The object is an %s." % "Apple" # a string using str()
The object is an Apple.
In [7]: print "The object is an %r." % "Apple" # a string using repr()
The object is an 'Apple'.
In [19]: z = {'a': 2, 'b': 3}
In [21]: print "a is %(a)d, and b is %(b)d." % z
a is 2, and b is 3.
You should be aware, however, that % formatting is no longer considered the "correct" way to do string formatting, and it isn't in Python 3 at all. Instead, both Python 2.6 and up, and Python 3 have the .format method on strings, which is less compact, but fits the rest of python much better (% is actually an overloaded modulo operator). As some examples:
In [39]: print "a is: {0}, or {0:g}, or {0:e}, and z is {1:s},\n and a in z is {1[a]}, \
....: but the a variable is {0:,}.".format(a,z)
a is: 1507.2515621, or 1507.25, or 1.507252e+03, and z is {'a': 2, 'b': 3},
and a in z is 2, but the a variable is 1,507.2515621.
This has many options, and I'd highly recommend reading the documentation on it. Unfortunately, it has what I feel are some unfortunate design choices, and the documentation is rather opaque.
A better example of when you would use the first method (percent formatting) would be
Y = 'Apple'
print "The %s tastes sweet." % Y
It allows you to easily insert variables into a string without having to do something like this:
Y = 'Apple'
print "The", Y, " tastes sweet."
So it's personal preference really, but percent formatting allows one to insert variables into a string without concatenation.
The former prints a single, formatted string. The latter prints two things, one after the other, separated by a space. Use string formatting when you want to put together a string, such as for use in a GUI element or as an argument to some processing function. Sending multiple objects to the print statement (or to the print() function in Python 3) is mostly for print debugging (although there's nothing wrong with using it in a command-line program, if the resulting code is as clear as what you'd create with string formatting).

Don't understand the %

I have searched stackoverflow and I can't find the answer that I am looking for. Apologies if this sounds like a dumb question since I am a newbie learning Python. Spent 1 hour trying to understand this and I can't grasp the concept.
Can somebody explain to me the following:
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
print joke_evaluation % hilarious
hilarious = "False"
joke_evaluation = "Isn't that joke so funny?!"
print hilarious + joke_evaluation
Why is it that you can't combine the first with + but %.
Is it because in the second one, they are both defined strings with quotations but in the first, hilarious = False is not in quotations?
The % operator on strings isn't exactly a concatenation like the + operator is.
With % you're actually substituting placeholders in the string on the left side of % with values from the right side.
So you could have something like this:
"This is my %s string" % "fantastic"
would yield:
This is my fantastic string
See how you're not concatenating the strings but "inserting" into the string on the right side.
See the documentation for more details.
Update:
As pointed out in the comments below, there are two "issues" with this. As of Python 2.5, this is actually the "old" way of doing string substitution. These days the following format is preferred (kudos to asmacdo)
"This is my {adjective} string".format(adjective='fantastic')
As well in the comments (thanks ErlVolton) I should explain that the "%s" refers to a string substitution. That is, the value that gets put in there should be a string. Similarly you can have integer substitution ("%d"), decimal floating point substitution ("%f") and, as in the case of the original question, you can substitute boolean values with "%r". You can also do a lot more formatting (vary the number of decimal places for a floating point number, pad numbers with leading zeros etc.) which is explained much better in the docs.
Finally, it's worth mentioning that you can substitute multiple values into a string but that changes the syntax a tiny bit. Instead of having a single value after the % operator you need to use a tuple. Example:
"this %s substitutes strings, booleans (%r) and an integer (%d)" % ('string', True, 42)
would yield:
this string substitutes strings, booleans (True) and an integer (42)
In this case, the percent sign marks the start of a printf-style specifier. When the first argument is a string, it formats it using the second argument (a boolean value in this case).
Refer to the documentation, or check out this question. They should shed some light on the situation.
As for the plus sign, you simply can't add (or concat) a boolean value to a string.

Not quite sure what the point of the %s is in Python, help?

I'm learning Python from a book right now and I can't figure out what the point is of using the %s to site a specific item in a list, string, dictionary, etc.
For example:
names = ["jones", "cohen", "smith", "griffin"]
print(names[1])
print("%s" % names[1])
Both commands print "cohen," what's the point of ever using the %s?
The idea is to allow you to easily create more complicated output like
print("The name is %s!" % names[1])
instead of
print("The name is " + names[1] + "!")
However, as you're just starting to use Python, you should start learning the new string formatting syntax right away:
print("The name is {}!".format(names[1])
Of course, this example can't show the real power of string formatting methods. You can do much more with those, for example (taken from the docs linked above):
>>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated
'abracadabra'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'
>>> coord = (3, 5)
>>> 'X: {0[0]}; Y: {0[1]}'.format(coord)
'X: 3; Y: 5'
>>> # format also supports binary numbers
>>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)
'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
and so on...
The idea of %s in python is for formating.
a = 1.23
print "The value is %0.5f" %(a) # prints 1.23000
%s is used to construct a string.
In python, like in many other languages, strings are immutable. So, if you concatenate a lot of strings, each of them is created and stored in the memory waiting to be garbage collected.
The point of %s, so, is, if you have to join many different strings, construct the string once and hence save unnecessary memory overhead.
It is also arguably a much more convenient syntax than the + and breaking strings where need to be.
print(names[1]) just prints the str() representation
print("%s" % names[1]) on the other hand prints the format string "%s" which is filled with names[1]
the effect here is the same.
with print(n1, n2, n3) you can print several data objects separated by a space. think of it as hard coded.
with print(" some format string " % (n1, n2, n3)) you can "beautify" your output. the format string could be a variable that you put together so this could change during runtime of the code.
Using %s is just using what I would call printf format. It's familiar from programming languages like C. As pointed out by Tim, python has a new preferred way to format strings which you should probably learn. But the old way is still pretty powerful. Try man sprintf to see how you can specify flags, field width, precision, etc. I think python's print is compatible with all that.

Categories

Resources