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).
Related
I have a function taking float arguments (generally integers or decimals with one significant digit), and I need to output the values in a string with two decimal places (5 → 5.00, 5.5 → 5.50, etc). How can I do this in Python?
Since this post might be here for a while, lets also point out python 3 syntax:
"{:.2f}".format(5)
You could use the string formatting operator for that:
>>> '%.2f' % 1.234
'1.23'
>>> '%.2f' % 5.0
'5.00'
The result of the operator is a string, so you can store it in a variable, print etc.
f-string formatting:
This was new in Python 3.6 - the string is placed in quotation marks as usual, prepended with f'... in the same way you would r'... for a raw string. Then you place whatever you want to put within your string, variables, numbers, inside braces f'some string text with a {variable} or {number} within that text' - and Python evaluates as with previous string formatting methods, except that this method is much more readable.
>>> foobar = 3.141592
>>> print(f'My number is {foobar:.2f} - look at the nice rounding!')
My number is 3.14 - look at the nice rounding!
You can see in this example we format with decimal places in similar fashion to previous string formatting methods.
NB foobar can be an number, variable, or even an expression eg f'{3*my_func(3.14):02f}'.
Going forward, with new code I prefer f-strings over common %s or str.format() methods as f-strings can be far more readable, and are often much faster.
String Formatting:
a = 6.789809823
print('%.2f' %a)
OR
print ("{0:.2f}".format(a))
Round Function can be used:
print(round(a, 2))
Good thing about round() is that, we can store this result to another variable, and then use it for other purposes.
b = round(a, 2)
print(b)
Use round() - mostly for display purpose.
String formatting:
print "%.2f" % 5
If you actually want to change the number itself instead of only displaying it differently use format()
Format it to 2 decimal places:
format(value, '.2f')
example:
>>> format(5.00000, '.2f')
'5.00'
Using python string formatting.
>>> "%0.2f" % 3
'3.00'
Shortest Python 3 syntax:
n = 5
print(f'{n:.2f}')
In Python 3
print(f"{number:.2f}")
A shorter way to do format.
I know it is an old question, but I was struggling finding the answer myself. Here is what I have come up with:
Python 3:
>>> num_dict = {'num': 0.123, 'num2': 0.127}
>>> "{0[num]:.2f}_{0[num2]:.2f}".format(num_dict)
0.12_0.13
I faced this problem after some accumulations. So What I learnt was to multiply the number u want and in the end divide it to the same number. so it would be something like this: (100(x+y))/100 = x+y if ur numbers are like 0.01, 20.1, 3,05.
You can use number * (len(number)-1)**10 if your numbers are in unknown variety.
If you want to get a floating point value with two decimal places limited at the time of calling input,
Check this out ~
a = eval(format(float(input()), '.2f')) # if u feed 3.1415 for 'a'.
print(a) # output 3.14 will be printed.
Using Python 3 syntax:
print('%.2f' % number)
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.
This question already has an answer here:
How can I concatenate str and int objects?
(1 answer)
Closed 1 year ago.
I'm new to Python, so I've been running through my own set of exercises to simply start memorizing basic functions and syntax.
I'm using the PyCharm IDE and Python 3.4. I've run into an issue when running through some basic string and integer concatenation exercises. Each instance below is throwing an unsupported operand type. There are several threads on Stack Overflow that clearly states proper concatenation syntax, but the above error message continues to plague me.
print ("Type string: ") + str(123)
print ("Concatenate strings and ints "), 10
In Python 3+, print is a function, so it must be called with its arguments between parentheses. So looking at your example:
print ("Type string: ") + str(123)
It's actually the same as:
var = print("Type string: ")
var + str(123)
Since print returns nothing (in Python, this means None), this is the equivalent of:
None + str(123)
which evidently will give an error.
That being said about what you tried to do, what you want do to is very easy: pass the print function what you mean to print, which can be done in various ways:
print ("Type string: " + str(123))
# Using format method to generate a string with the desired contents
print ("Type string: {}".format(123))
# Using Python3's implicit concatenation of its arguments, does not work the same in Python2:
print ("Type string:", str(123)) # Notice this will insert a space between the parameters
Note that print is a function in Python 3. In Python 2, your first line would concatenate "Type string: " and "123" and then print them. In Python 3, you are calling the print function with one argument, which returns None, and then add "123" to it. That doesn't make any sense.
The second line doesn't generate an error in Python 2 or 3 (I've tested it with 2.7.7 and 3.2.3). In Python 2, you get
Concatenate strings and ints 10
while in Python 3, your script should only print
Concatenate strings and ints
This is because again, print is a function, and therefore you call it with the argument "Concatenate strings and ints". The , 10 makes your line a tuple of the return value of print, which is None, and 10. Since you don't use that tuple for anything, there is no visible effect.
Try format():
print("Type string: {}".format(123))
print("Concatenate strings and ints {}".format(10))
There is nothing wrong with this:
print ("Type string: ") + str(123)
print is just a function like anything else. And you're calling that function with one argument, "Type string: ", and then trying to add the result (which will be None) to the string '123'. That isn't going to work. If you wanted to add the two strings together, you have to put them into the same expression, inside the parentheses:
print("Type string: " + str(123))
Similarly:
print ("Concatenate strings and ints "), 10
This calls print with one argument, and then makes a tuple of the None returned by print and the number 10. If you want to pass 10 to the print call, it has to go inside the parentheses:
print("Concatenate strings and ints ", 10)
As gitaarik's answer points out, using str.format is more flexible, and avoids the possibility of problems like this. It also gives you code that works exactly the same way in both Python 2.6-2.7 and Python 3.x, which is pretty nice even if you aren't trying to write dual-platform/single-codebase code, because it'll be understandable even to people who only know one or the other.
I think this is a pretty cool way to concatenate a string and an int in Python:
print (f"Type string: {123}")
print (f"Concatenate strings and ints {10}")
You can do it like this:
c = 'Emerson'
d = 32
print("My name is %s and I am %d years old." %(c,d))
Result:
My name is Emerson and I am 32 years old.
I have a variable that I need to write with different precisions depending on the case, sometimes I'll need two decimal places and other times more.
Recently I've been trying to use the string.format() method instead of the % operator but I can't figure out how to do this apparently simple thing.
Here's a MWE:
# Some variable.
a=5.2365548
# Define two precisions.
x, y = 2, 5
# Print 'a' with different precisions.
print 'The variable equals: {:.xf}'.format(a)
print 'The variable equals: {:.yf}'.format(a)
which would ideally return in each case:
The variable equals: 5.24
The variable equals: 5.23655
Of course using :.xf doesn't work but I believe it shows what I need.
>>> print '{:.{prec}f}'.format(12.345, prec=2)
12.35
>>> print '{:.{prec}f}'.format(12.345, prec=1)
12.3
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.