I am a beginner and learning Python. My question is python can read a variable in a string without format identifier, then why has format identifiers been provided for?
Ex:
carPoolTotal = 4
print "We have total", carPoolTotal, "people in carpooling."
print "We have total %d people in carpooling." % carPoolTotal
Both works the same thing, then why exactly is identifier introduced in Python?
Format identifiers help if you want to provide non-default formatting for your values. For example, you might want to format a long decimal as a decimal with a maximum of two decimal places.
Related
I have been aware of .format for a long while now but when I tried to include float formatting in a string like below:
"ab_{}_cd{}_e_{}_{}_{}_val={0:.5f}_{}".format(string1,str(2),string2,string3,string4,str(0.12345678),string5)
In the above example string1-5 denote random strings included for this example.
Returned the following error ValueError: cannot switch from automatic field numbering to manual field specification
After some searching this question does seem to hold the solution Using .format() to format a list with field width arguments
The above link shows I need to format all of the {} in the string to achieve the formatting I want. I have glanced at official documentation https://docs.python.org/2/library/string.html and https://docs.python.org/2/library/stdtypes.html#str.format and there isn't much in the way of explaining what I'm looking for.
Desired output:
An explanation as to how I can convert the automatic field specification of the .format option to a manual field specification with only formatting the float variable I have supplied and leaving all other string1-5 variables unformatted. Whilst I could just use something like round() or a numpy equivalent this might cause issues and I feel like I would learn better with the .format example.
in your code remove the zero before the rounded digit
"ab_{}_cd{}_e_{}_{}_{}_val={:.5f}_{}".format(string1,str(2),string2,string3,string4,str(0.12345678),string5)
NOTE: why it did not work is , you can either mention index in {} as {0},{1} or leave all of them, but you cannot keep few {} with index and few without any index.
Following from this question Stackoverflow question the answer provided has ':.' character inside the print statement. i.e
a=13.946
print("{0:.2f}".format(a))
My question is what is the ':.' called? i want to search it and learn what other options there are.
They are separate things.
The .2f is a part of the format specifier which says print only the first two digits after the decimal point.
The : is another part of the format specifier as described here:
"Each field can also specify an optional set of 'format
specifiers' which can be used to adjust the format of that field.
Format specifiers follow the field name, with a colon (':')
character separating the two:"
"My name is {0:8}".format('Fred')
Outputs 'Fred' plus 4 spaces to make 8 characters:
'My name is Fred '
According to Pythong strings library 7.1.3 - Format string syntax, shows that you can add a format_spec
a format_spec, which is preceded by a colon ':' These specify a non-default format for the replacement value.
Format Specification Mini-Language shows you the whole list of options available and the context on how they can be used.
Python 2.7
:. is two separate thing.
Don't get confuse and be fool by its deception and theatric
Hint ':' follow by '.'
The colon is a format spec
The dot is a leading path to mini-language , in this case 2f
There is no such character as :.. What you are seeing here is : followed by .2f which means a floating point number with 2 decimals.
In this code:
a=13.946
print("{0:.2f}".format(a))
The command being given in the print is convert the float into a two decimal place string.
This would print 13.95
Test it with some more statements, then you will understand it more:-
a = 13.946
print("{0:.2f}".format(a))
a = 13.946
print("{1:.2f}".format(a, 10))
a = 13.946
print("{2:.2f}".format(a, 10, 12))
a = 13.946
print("{3:.2f}".format(a, 10, 12))
Here is brief:-
.2f means format your number with 2 decimal places.
0 says you need to select first item passed to format.
:. is nothing but these 2 are separate thing. : is separate between item and format
I've been looking around and I've been unable to find a definitive answer to this question: what's the recommended way to print variables in Python?
So far, I've seen three ways: using commas, using percent signs, or using plus signs:
>>> a = "hello"
>>> b = "world"
>>> print a, "to the", b
hello to the world
>>> print "%s to the %s" % (a, b)
hello to the world
>>> print a + " to the " + b
hello to the world
Each method seems to have its pros and cons.
Commas allow to write the variable directly and add spaces, as well as automatically perform a string conversion if needed. But I seem to remember that good coding practices say that it's best to separate your variables from your text.
Percent signs allow that, though they require to use a list when there's more than one variable, and you have to write the type of the variable (though it seems able to convert even if the variable type isn't the same, like trying to print a number with %s).
Plus signs seem to be the "worst" as they mix variables and text, and don't convert on the fly; though maybe it is necessary to have more control on your variable from time to time.
I've looked around and it seems some of those methods may be obsolete nowadays. Since they all seem to work and each have their pros and cons, I'm wondering: is there a recommended method, or do they all depend on the context?
Including the values from identifiers inside a string is called string formatting. You can handle string formatting in different ways with various pros and cons.
Using string concatenation (+)
Con: You must manually convert objects to strings
Pro: The objects appear where you want to place the into the string
Con: The final layout may not be clear due to breaking the string literal
Using template strings (i.e. $bash-style substitution):
Pro: You may be familiar with shell variable expansion
Pro: Conversion to string is done automatically
Pro: Final layout is clear.
Con: You cannot specify how to perform the conversion
Using %-style formatting:
Pro: similar to formatting with C's printf.
Pro: conversions are done for you
Pro: you can specify different type of conversions, with some options (e.g. precision for floats)
Pro: The final layout is clear
Pro: You can also specify the name of the elements to substitute as in: %(name)s.
Con: You cannot customize handling of format specifiers.
Con: There are some corner cases that can puzzle you. To avoid them you should always use either tuple or dict as argument.
Using str.format:
All the pros of %-style formatting (except that it is not similar to printf)
Similar to .NET String.Format
Pro: You can manually specify numbered fields which allows you to use a positional argument multiple times
Pro: More options in the format specifiers
Pro: You can customize the formatting specifiers in custom types
The commas do not do string-formatting. They are part of the print statement statement syntax.
They have a softspace "feature" which is gone in python3 since print is a function now:
>>> print 'something\t', 'other'
something other
>>> print 'something\tother'
something other
Note how the above outputs are exactly equivalent even though the first one used comma.
This is because the comma doesn't introduce whitespace in certain situations (e.g. right after a tab or a newline).
In python3 this doesn't happen:
>>> print('something\t', 'other')
something other
>>> print('something\tother') # note the difference in spacing.
something other
Since python2.6 the preferred way of doing string formatting is using the str.format method. It was meant to replace the %-style formatting, even though currently there are no plans (and I don't there will ever be) to remove %-style formatting.
string.format() basics
Here are a couple of example of basic string substitution, the {} is the placeholder for the substituted variables. If no format is specified, it will insert and format as a string.
s1 = "so much depends upon {}".format("a red wheel barrow")
s2 = "glazed with {} water beside the {} chickens".format("rain", "white")
You can also use the numeric position of the variables and change them in the strings, this gives some flexibility when doing the formatting, if you made a mistake in the order you can easily correct without shuffling all variables around.
s1 = " {0} is better than {1} ".format("emacs", "vim")
s2 = " {1} is better than {0} ".format("emacs", "vim")
The format() function offers a fair amount of additional features and capabilities, here are a few useful tips and tricks using .format()
Named Arguments
You can use the new string format as a templating engine and use named arguments, instead of requiring a strict order.
madlib = " I {verb} the {object} off the {place} ".format(verb="took", object="cheese", place="table")
>>> I took the cheese off the table
Reuse Same Variable Multiple Times
Using the % formatter, requires a strict ordering of variables, the .format() method allows you to put them in any order as we saw above in the basics, but also allows for reuse.
str = "Oh {0}, {0}! wherefore art thou {0}?".format("Romeo")
>>> Oh Romeo, Romeo! wherefore art thou Romeo?
Use Format as a Function
You can use .format as a function which allows for some separation of text and formatting from code. For example at the beginning of your program you could include all your formats and then use later. This also could be a nice way to handle internationalization which not only requires different text but often requires different formats for numbers.
email_f = "Your email address was {email}".format
print(email_f(email="bob#example.com"))
Escaping Braces
If you need to use braces when using str.format(), just double up
print(" The {} set is often represented as {{0}} ".format("empty"))
>>> The empty set is often represented as {0}
the question is, wether you want print variables (case 1) or want to output formatted text (case 2). Case one is good and easy to use, mostly for debug output.
If you like to say something in a defined way, formatting is the better choice. '+' is not the pythonic way of string maipulation.
An alternative to % is "{0} to the {1}".format(a,b) and is the preferred way of formatting since Python 3.
Depends a bit on which version.
Python 2 will be simply:
print 'string'
print 345
print 'string'+(str(345))
print ''
Python 3 requires parentheses (wish it didn't personally)
print ('string')
print (345)
print ('string'+(str(345))
Also the most foolproof method to do it is to convert everything into a variable:
a = 'string'
b = 345
c = str(345)
d = a + c
I have a huge list of numbers (each number is less or equal to 6 numbers) in my database like that :
90494
898333
898
13
etc..
And I would like to have them formatted like that, using python :
090494
898333
000898
000013
etc...
Thanks a lot for your help
Standard python interpolation with C-style format modifiers should work:
print "%06d" % number
Or, if you prefer .format described in PEP 3101 (most likely the future of string formatting in python):
print '{0:06d}'.format(1)
Or, if you're working with strings, you can use zfill:
print '1'.zfill(6)
Alex's answer has the following line when translated to English
print "%2d. %8.2f %8.2f %8.2f" % (
i, payment, interest, monthPayment)
I am unsure about the line
"%2d. %8.2f %8.2f %8.2f" % #Why do we need the last % here?
It seems to mean the following
apply %2d. to i
apply %8.2f to payment
apply %8.2f to interest
apply %8.2f to monthPayment
The %-words seem to mean the following
%2d.: a decimal presentation of two decimals
2-4. %8.2f: a floating point presentation of two decimals
I am not sure why we use the 8 in %8.2f.
How do you understand the challenging line?
The 8 in 8.2 is the width
"Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger"
The 2 is the number of decimal places
The final % just links the format string (in quotes) with the list of arguments (in brackets).
It's a bit confusing that they chose a % to do this - there is probably some deep python reason.
edit: Apparently '%' is used simply because '%' is used inside the format - which is IMHO stupid and guaranteed to cause confusion. It's like requiring an extra dot at the end of a floating point number to show that it's floating point!
The last % is an operator that takes the string before it and the tuple after and applies the formatting as you note. See the Python tutorial for more details.
The % is an operator which makes a format string. A simple example would be:
"%s is %s" % ( "Alice", "Happy" )
Which would evaluate to the string "Alice is Happy". The format string that is provided defines how the values you pass are put into the string; the syntax is available here. In short the d is "treat as a decimal number" and the 8.2 is "pad to 8 characters and round to 2 decimal places". In essence it looks like that format in particular is being used so that the answers line up when viewed with a monospace font. :)
In my code example the s means "treat as a string".
The % after a string tells Python to attempt to fill in the variables on the left side of the
'%' operator with the items in the list on the right side of the '%' operator.
The '%' operator knows to find the variable in the string by looking for character in the string starting with %.
Your confusion is that you think the % operator and the % character in the string are the same.
Try to look at it this way, outside a string % is an operator, inside a string it is possibly a template for substitution.
As usual, a quote of the doc is required - string-formatting:
String and Unicode objects have one unique built-in operation: the % operator (modulo). This is also known as the string formatting or interpolation operator. Given format % values (where format is a string or Unicode object), % conversion specifications in format are replaced with zero or more elements of values. The effect is similar to the using sprintf in the C language.
And the description of the conversion specifier to explain %8.2f
A conversion specifier contains two or more characters and has the following components, which must occur in this order:
The '%' character, which marks the start of the specifier.
Mapping key (optional), consisting of a parenthesised sequence of characters (for example, (somename)).
Conversion flags (optional), which affect the result of some conversion types.
Minimum field width (optional). If specified as an '*' (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision.
Precision (optional), given as a '.' (dot) followed by the precision. If specified as '*' (an asterisk), the actual width is read from the next element of the tuple in values, and the value to convert comes after the precision.
Length modifier (optional).
Conversion type.
When the right argument is a dictionary (or other mapping type), the format string includes mapping keys (2). Breaking the example to 2 steps, we have a dictionary and a format that includes keys from the dictionary (the # is a key):
>>> mydict = {'language':'python', '#':2}
>>> '%(language)s has %(#)03d quote types.' % mydict
'python has 002 quote types.'
>>>
the %8.2f means allow 8 character spaces to hold the number given by the corrisponding variable holding a float, and then have decimal precision of 2.