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.
Related
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).
What is the best way to display either a + in front, for a float? Lets say if a user inputs the number "10". I want to have a "+" appear in front of it since it is a positive number. If it were a negative number then I would leave it as it is.
Would I have to use an if statement and then convert it to a string and then add in the + sign? Or is there an easier way?
Use the format() function:
>>> format(10, '+f')
'+10.000000'
>>> format(-10, '+f')
'-10.000000'
>>> format(3.14159, '+.3f')
'+3.142'
See the Format Specification Mini-Language for the specific formatting options; prepending a number format with + makes it include a plus for positive numbers, - for negative. The last example formats the number to use 3 decimals, for example.
If you need to remove the negative sign, you'd have to do so explicitly using .lstrip():
>>> format(10, '+f').lstrip('-')
'+10.000000'
>>> format(-10, '+f').lstrip('-')
'10.000000'
but that'd be quite confusing a specification to read, in my opinion. :-)
Use formatting - and then remove any leading - from the result:
print format(10, '+').lstrip('-')
The first thing I thought:
userInput=int(input("Enter number: "))
if userInput > 0:
print ("+"+userInput)
else:
pass
Formatting is just the way to go though, faster and cleaner.
I feel like this is a simple question, but it keeps escaping me...
If I had a string, say, "1010101", how would I refer to the first digit in the string by its index?
You can get the first element of any sequence with [0]. Since a string is a sequence of characters, you're looking for s[0]:
>>> s = "1010101"
>>> s[0]
'1'
For a detailed explanation, refer to the Python tutorial on strings.
Negative indexes count from the right side.
digit = mystring[-1]
In Python, a sting is something called, subscriptable. That means that you can access the different parts using square brackets, just like you can with a list.
If you want to get the first character of the string, then you can simply use my_string[0].
If you need to get the last (character) in a string (the final 1 in the string you provided), then use my_string[-1].
If you originally have an int (or a long) and you are looking for the last digit, you are best off using % (modulous) (10101 % 10 => 1).
If you have a float, on the other hand, you are best of str(my_float)[-1]
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.