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.
Related
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.
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
I'm wondering how to round a number in python while using string formatting. In my code, I used %r instead of %d, beacuse %d prints an interger. How do I round the numbers while using %r? I would like to have my numbers rounded to two decimal places.
def new_formula(value):
payment = value * 9.00
tips = payment/.29
earned = payment + tips
return payment, tips, earned
name = "Nate"
hours = 7.5
print "%s worked %r hours." % (name, hours)
print """He was paid %r dollars and made %r dollars in tips.
At the end of the day he earned %r dollars.""" % new_formula(hours)
Well, you could always round the return statement. So, round(payment, 2) for example. And, I am not sure why you are using \r. (Could you tell me why?). You could do %.2f to use two decimal places instead.
Use the function round:
print "%s worked %.2f hours." % (name, round(hours, 2))
The parameter 2 tells the function to use 2 digits after the decimal point.
I'm making a unit converter just to practice. Currently, I've defined a function to figure out what type of conversion to make (distance, time, mass, etc.).
It then calls the correct converter for the type, asks what you're converting from, what you're converting to, and what the value for conversion is.
def mass_converter():
convert_from = raw_input('What unit are you converting from? ')
convert_to = raw_input('What unit are you converting to? ')
value = raw_input('How many of those do you have? ')
if convert_from == "pounds" and convert_to == "kilograms":
answer = float(value) * 0.453592
print "That many pounds is %d kilograms." % answer
elif convert_from == "kilograms" and convert_to == "pounds":
answer = float(value) * 2.20462
print "That many kilograms is %d pounds." % answer
else:
print "You have not selected a valid unit; please try again."
mass_converter()
Currently, if I were to convert 10 pounds to kilograms, it tells me that the answer is 4 kilograms. It seems to be chopping off my decimals. Obviously int(value) will do the same thing. What can I use to keep the exact value entered by the user?
The problem here is that you're using the %d format modifier in your string formatting which casts your answer to an integer. Use %f instead (or even %s).
You could use %f instead of %d. %d formats the number not as a floating point, but as a integer. Alternatively you could use
print "That many kilograms is {} pounds.".format(answer)
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.