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.
Related
I want to have a string where I can format it with an integer so that it:
Adds a sign in front of the integer (+ for positive ints, - for negative ints)
Surround the signed int with parentheses (i.e. with ())
Left align the int with parentheses on the left, adding if necessary spaces to the end.
I know how to do these steps separately, but I haven't been able to combine them into a single string.
1 and 2 would be accomplished with for example '({:+d})'.format(3), this would result in (+3).
3 is done for an arbitrary string with '{:<5}'.format(3), this would result in 3 (4 trailing spaces).
My goal is to have a single string where I can call .format on only once, so
format_string.format(3)
would result in
(+3)
with one trailing space to make the string length 5.
Is this possible?
I've tried ({{:+d}:<5}) but this doesn't work as it thinks {:+d} is the field name to format with <5, which is obviously not the case.
I've also looked into f-strings, but these are not suitable for my use case as I call .format on the format string later than when it's created.
Any help would be most welcome!
Solution with one call for format:
def special_format_int(n, SPACES=5):
return '({:+d})'.format(n).ljust(SPACES)
I am trying to pack a string using struct.pack.
I am able to see complete value if I use integer type but when I want to use string I only see one character.
struct.pack("<1L",0xabcdabcd)
'\xab\xcd\ab\cd'
struct.pack("<1s","overflow")
'o' prints just s. I wanted it to print full string: overflow.
In the format string ("<1s") you're passing to struct.pack, the 1 denotes the maximum number of characters that field can store. (See the paragraph beginning "For the 's'..." in the struct documentation.) Since you're passing 1, it will only store the first character. You'll need to choose a length that will fit any string you want to store in the struct, and specify that. For example, to store the string "overflow" (8 characters) you could use "<8s":
>>> struct.pack("<8s", "overflow")
'overflow'
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
s='s=%r;print(s%%s)';print(s%s)
I understand % is to replace something in a string by s (but actually who to replace?)
Maybe more intriguing is, why the print(s%%s) become print(s%s) automatically after %s is replaced by s itself?
The "%%" you see in that code is a "conversion specifier" for the older printf-style of string formatting.
Most conversion specifiers tell Python how to convert an argument that is passed into the % format operator (for instance, "%d" says to convert the next argument to a decimal integer before inserting it into the string).
"%%" is different, because it directly converts to a single "%" character without consuming an argument. This conversion is needed in the format string specification, since otherwise any "%" would be taken as the first part of some other code and there would be no easy way to produce a string containing a percent sign.
The code you show is a quine (a program that produces its own code as its output). When it runs print(s%s), it does a string formatting operation where both the format string, and the single argument are the same string, s.
The "%r" in the string is a conversion specifier that does a repr of its argument. repr on a string produces the string with quotes around it. This is where the quoted string comes from in the output.
The "%%" produces the % operator that appears between the two s's in the print call. If only one "%" was included in s, you'd get an error about the formatting operation expecting a second argument (since %s is another conversion specifier).
print '% %s' % '' #wrong
print '%% %s' % '' #correct and print '% '
Think about \\ and \.
In Python v2.6 I can get hexadecimal for my integers in one of two ways:
print(("0x%x")%value)
print(hex(value))
However, in both cases, the hexadecimal digits are lower case. How can I get these in upper case?
Capital X (Python 2 and 3 using sprintf-style formatting):
print("0x%X" % value)
Or in python 3+ (using .format string syntax):
print("0x{:X}".format(value))
Or in python 3.6+ (using formatted string literals):
print(f"0x{value:X}")
Just use upper().
intNum = 1234
hexNum = hex(intNum).upper()
print('Upper hexadecimal number = ', hexNum)
Output:
Upper hexadecimal number = 0X4D2
print(hex(value).upper().replace('X', 'x'))
Handles negative numbers correctly.
By using uppercase %X:
>>> print("%X" % 255)
FF
Updating for Python 3.6 era: Just use 'X' in the format part, inside f-strings:
print(f"{255:X}")
(f-strings accept any valid Python expression before the : - including direct numeric expressions and variable names).
The more Python 3 idiom using f-strings would be:
value = 1234
print(f'0x{value:X}')
'0x4D2'
Notes (and why this is not a duplicate):
shows how to avoid capitalizing the '0x' prefix, which was an issue in other answers
shows how to get variable interpolation f'{value}'; nobody actually ever puts (hardcoded) hex literals in real code. There are plenty of pitfalls in doing variable interpolation: it's not f'{x:value}' nor f'{0x:value}' nor f'{value:0x}' nor even f'{value:%x}' as I also tried. So many ways to trip up. It still took me 15 minutes of trial-and-error after rereading four tutorials and whatsnew docs to get the syntax. This answer shows how to get f-string variable interpolation right; others don't.