This question already has answers here:
What's the difference between %s and %d in Python string formatting?
(13 answers)
Closed 1 year ago.
I have been studying pickling and unpickling and a came across this - can someone please explain what it stands for?
This is the code that led to the confusion
% means parameter passed into the string.
%s is parameter that should be treated as string
There are some other kinds of parameters types used there like %d for decimal integers, %f for floating point numbers etc.
The %s is a placeholder for strings using the old formatting methods in python. Essentially %s gets replaced by the string value of my_int in your example. Here is some documentation provided by #Paul Cornelius: https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting.
There are a few newer ways to do this if you want to in your own code that work a bit better, pickle likely uses the old style because they have no real reason to upgrade.
F-strings
in python 3.6+ you can use fstrings by putting an f in front of a string declaration and using {variable_name} to access a value. like in this example:
name = "John Smith" # A dummy name
email_count = 3 # A representation of users # of new emails
current_temperature = 20.3567 # A representation of the current temperature in celsius
greeting = f"Hello, {name} The weather today is {current_temperature} degrees. You have {email_count} new emails."
print(greeting)
Which would result in printing
Hello John Smith The weather today is 20.3567 degrees. You have 3 new emails.
This is equivalent using the % method to doing:
name = "John Smith" # A dummy name
email_count = 3 # A representation of users # of new emails
current_temperature = 20.3567 # A representation of the current temperature in celsius
greeting = "Hello, %s The weather today is %03.2f degrees. You have %d new emails." % (name, current_temperature, email_count)
print(greeting)
Where %s is replaced by a string, %03.2f is replaced by a float rounded to the nearest 2 decimal places, and %d is replaced by an integer. One of the main reasons this method got replaced is because F-strings are easier to read, and don't require you to know the types of everything being put into them ahead of time (just uses the __repr__() of the object), whereas for example %d will only work with integers, or objects that can have int(obj) called on them.
Related
So I was looking at a python tutorial, and in a statement, it used %.
print ("Total Employee %d" % Employee.empCount)
Can someone please take their time and describe to me what that means. I'm pretty sure that it doesn't signify a division.
Python uses C-style string formatting to create new, formatted
strings. The "%" operator is used to format a set of variables
enclosed in a "tuple" (a fixed size list), together with a format
string, which contains normal text together with "argument
specifiers", special symbols like "%s" and "%d".
the % sign in this case is supposed to be used for string formatting. This is an old technique and can be used with and f-string now. % is mostly used in java and not python.
% Employee.empCount is a variable and %d for print integer variable.That's mean value of variable % Employee.empCount print in place of %d.
% sign use for give reference of variable.
Python Program for
Old Style Formatting
of Integers also used %
Integer1 = 12.3456789
print("Formatting in 3.2f format: ")
print('The value of Integer1 is %3.2f' %Integer1)
print("\nFormatting in 3.4f format: ")
print('The value of Integer1 is %3.4f' %Integer1)
Output:
Formatting in 3.2f format:
The value of Integer1 is 12.35
Formatting in 3.4f format:
The value of Integer1 is 12.3457
also use as
print("writing integer in a string: %s" %Integer1)
output
writing integer in a string: 12.3456789
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)))
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).
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.
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.