what does % mean in python when writing a string - python

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

Related

What does %s" % stand for in a Python print statement [duplicate]

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.

Trying to understand binary conversion script

I have the following python code, which converts a binary string into plain-text:
import bin ascii
n = int('01100001011000100110001101100100', 2)
binascii.unhexlify('%x' % n)
This code functions properly, but I don't understand what's going on here.
What is the purpose of the "2" at the end of the int declaration?
What is the purpose of the "'%x' % n" argument?
What is the purpose of the 2 at the end of the int declaration?
According to the documentation, int can take a second argument: the base of the first argument.
What is the purpose of the '%x' % n argument?
%x in a string indicates that an item will be formatted to hexadecimal with lowercase letters. '%x' % n. It is similar to the builtin hex function, except it doesn't have the leading 0x in the string. An equivalent expression would be format(n, 'x').

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.

Python 2.7: %d, %s, and float()

I am attempting to teach myself a little coding through the "learn python the hard way" book and am struggling with %d / %s / %r when tying to display a floating point number. How do you properly pass a floating point number with a format character? First I tried %d but that made my answers display as integers.... I had some success with %r, but I was under the assumption that was usually reserved for debugging? I figured out for division in python 2.x you have to manually float the denominator for it to properly work for some reason.
Example code:
def divide (a, b):
print "WE DIVIDING %r and %r NOW" % (a, b)
return a / float(b)
print "Input first number:"
first = float(raw_input("> "))
print "OK, now input second number:"
second = float(raw_input("> "))
ans = divide(first, second)
print "DONE: %r DIVIDED BY %r EQUALS %r, SWEET MATH BRO!" % (first, second, ans)
See String Formatting Operations:
%d is the format code for an integer. %f is the format code for a float.
%s prints the str() of an object (What you see when you print(object)).
%r prints the repr() of an object (What you see when you print(repr(object)).
For a float %s, %r and %f all display the same value, but that isn't the case for all objects. The other fields of a format specifier work differently as well:
>>> print('%10.2s' % 1.123) # print as string, truncate to 2 characters in a 10-place field.
1.
>>> print('%10.2f' % 1.123) # print as float, round to 2 decimal places in a 10-place field.
1.12
Try the following:
print "First is: %f" % (first)
print "Second is: %f" % (second)
I am unsure what answer is. But apart from that, this will be:
print "DONE: %f DIVIDED BY %f EQUALS %f, SWEET MATH BRO!" % (first, second, ans)
There's a lot of text on Format String Specifiers. You can google it and get a list of specifiers. One thing I forgot to note:
If you try this:
print "First is: %s" % (first)
It converts the float value in first to a string. So that would work as well.

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