Understanding an uncommon python syntax - python

This is a hackerrank practice problem https://www.hackerrank.com/challenges/python-string-formatting/problem . It is not actually a difficult problem, but one of the solutions posted in the discussion is confusing. I am adding their function for doing the same below:
def print_formatted(number):
p = len(f"{number:b}")
for i in range(1,number+1): print(f"{i: >{p}} {i: >{p}o} {i: >{p}X} {i: >{p}b}")
Even though b is not defined it is not throwing an error. If I just do 5:6 in python, it throws an error. But if I do print(f"{5:6}"), it prints adds 6 spaces before 5 and prints it. What exactly is happening here and what are the common use cases for this?
What exactly is happening in the print statement? What does all the o, X nd b do? Why is there a {} inside one active {} and what does it do?

Format Specification Mini-Language
“Format specifications” are used within replacement fields contained
within a format string to define how individual values are presented
(see Format String Syntax and Formatted string literals). They can
also be passed directly to the built-in format() function. Each
formattable type may define how the format specification is to be
interpreted.
The available integer presentation types are:
Type
Meaning
'b'
Binary format. Outputs the number in base 2.
'c'
Character. Converts the integer to the corresponding unicode character before printing.
'd'
Decimal Integer. Outputs the number in base 10.
'o'
Octal format. Outputs the number in base 8.
'x'
Hex format. Outputs the number in base 16, using lower-case letters for the digits above 9.
'X'
Hex format. Outputs the number in base 16, using upper-case letters for the digits above 9. In case '#' is specified, the prefix '0x' will be upper-cased to '0X' as well.
'n'
Number. This is the same as 'd', except that it uses the current locale setting to insert the appropriate number separator characters.
None
The same as 'd'.
Source

Related

How to print whole number without zeros after decimal point?

I'm trying to print a whole number (such as 39 for example) in the following format: 39.
It must not be a str type object like '39.' for example, but a number
e. g. n = 39.0 should be printed like 39.
n = 39.0
#magic stuff with output
39.
I tried using :.nf methods (:.0f apparently -- didn't work), print(float(39.)) or just print(39.)
In the first case, it looks like 39, in the second and third 39.0
I also tried float(str(39) + '.') and obviously it didn't work
Sorry, if it's a stupid question, I've been trying to solve it for several hours already, still can't find any information.
From Format Specification Mini-Language (emphasis mine):
The '#' option causes the “alternate form” to be used for the conversion. The alternate form is defined differently for different types. This option is only valid for integer, float and complex types. For integers, when binary, octal, or hexadecimal output is used, this option adds the respective prefix '0b', '0o', '0x', or '0X' to the output value. For float and complex the alternate form causes the result of the conversion to always contain a decimal-point character, even if no digits follow it. Normally, a decimal-point character appears in the result of these conversions only if a digit follows it. In addition, for 'g' and 'G' conversions, trailing zeros are not removed from the result.
>>> n=39.0
>>> print(f'{n:#.0f}')
39.
print(int(n))
or u can try:
n = n // 1
print(f”{n}.”)

Remove decimal number from the function eval() [duplicate]

I want my Python (2.4.3) output numbers to have a certain format. Specifically, if the number is a terminating decimal with <= 6 significant digits, show it all. However, if it has > 6 significant digits, then output only 6 significant digits.
"A" shows how Python is writing the floats. "B" shows how I want them written. How can I make Python format my numbers in that way?
A:
10188469102.605597
5.5657188485
3.539
22.1522612479
0
15.9638450858
0.284024
7.58096703786
24.3469152383
B:
1.01885e+10
5.56572
3.539
22.1523
0
15.9638
0.284024
7.58097
24.3469
You'll want the g modifier for format that drops insignificant zeroes;
>>> "{0:.6g}".format(5.5657188485)
'5.56572'
>>> "{0:.6g}".format(3.539)
'3.539'
Sorry, my update also includes the fact that I am restricted to using
Python 2.4.3, which does not have format() function.
The format specifiers work even without the .format() function:
>>> for i in a:
... print '%.6g' % (i,)
...
1.01885e+10
5.56572
3.539
22.1523
0
15.9638
0.284024
7.58097
24.3469
There is a way to retain trailing zeros so that it consistently shows the number of significant digits. Not exactly what OP wanted, but probably useful to many.
a = [10188469102.605597,5.5657188485,3.539,22.1522612479,0,15.9638450858,0.284024,7.58096703786,24.3469152383]
for i in a:
print("{:#.6g}".format(i))
Output
1.01885e+10
5.56572
3.53900
22.1523
0.00000
15.9638
0.284024
7.58097
24.3469
Note that this will only work with the format function and not with % operator.
According to the docs:
The '#' option causes the “alternate form” to be used for the conversion. The alternate form is defined differently for different types. This option is only valid for integer, float, complex and Decimal types.
'g': General format ... insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it, unless the '#' option is used.
try this way
a=[10188469102.605597,5.5657188485,3.539,22.1522612479,0,15.9638450858,0.284024,7.58096703786,24.3469152383]
for i in a:
if i >100:
print '{:.6e}'.format(i)
else:
print '{:.6f}'.format(i)
for lower version of python
for i in a:
if i >100:
print '%6e'%i
else:
print '%6f'%i
output
1.018847e+10
5.565719
3.539000
22.152261
0.000000
15.963845
0.284024
7.580967
24.346915

Python define bitwise

I have a function that accepts 'data' as a parameter. Being new to python I wasn't really sure that that was even a type.
I noticed when printing something of that type it would be
b'h'
if I encoded the letter h. Which dosen't make a ton of sense to me. Is there a way to define bits in python, such as 1 or 0. I guess b'h' must be in hex? Is there a way for me to simply define an eight bit string
bits1 = 10100000
You're conflating a number of unrelated things.
First of all, (in Python 3), quoted literals prefixed with b are of type bytes -- that means a string of raw byte values. Example:
x = b'abc'
print(type(x)) # will output `<class 'bytes'>`
This is in contrast to the str type, which is a (Unicode) string.
Integer literals can be expressed in binary using an 0b prefix, e.g.
y = 0b10100000
print(y) # Will output 160
For what I know, 'data' is not a type. Your function (probably) accepts anything you pass to it, regardless of its type.
Now, b'h' means "the number (int) whose binary sequence maps to the char ´h´", this is not hexadecimal, but a number with possibly 8 bits (1 byte, which is the standard size for int and char).
The ASCII code for ´h´ is 104 (decimal), written in binary that would be b'\b01101000', or in hexa b'\x68'.
So, here is the answer I think you are looking for: if you want to code an 8-bit int from its binary representation just type b'\b01101000' (for 104). I would recommend to use hexa instead, to make it more compact and readable. In hexa, every four bits make a symbol from 0 to f, and the symbols can be concatenated every four bits to form a larger number. So the bit sequence 01101000 is written b'\b0110\b1000' or b'\x6\x8', which can be written as b'\x68'. The preceding b, before the quote marks tells python to interpret the string as a binary sequence expressed in the base defined by \b or \x (or \d for decimal), instead of using escape characters.

How to convert octal to string without change the value?

How to convert 00024 to '00024' with python?
If I run 00024 in python shell, it print 20 as result. I want to convert 00024 to string, with the result is '00024'. Any suggestions?
If you want to represent integers with leading zeros, format() the number to a string explicitly:
format(integer, '05d')
Whenever you output values, print implicitly converts it to a string with str(), with format() you get to control how that conversion takes place explicitly.
When you echo a number in the interactive interpreter, repr() is used instead, but for integers the output is exactly the same as when you use str().
Demo:
>>> format(24, '05d')
'00024'
When you enter 00024 as an integer literal, Python 2 parses that as an octal number, in Python 3 that's a syntax error.
If you want to interpret such a number in the Python 2 shell as if it was a string, you cannot do what you want, not with an arbitrary number of leading zeros. You can, at best, re-format the resulting integer as octal, again with leading zeros. That'll produce a string again, but you have to hardcode the number of leading zeros:
>>> number = 00024
>>> format(number, '05o')
'00024'
Note that this'll also fail as soon as you have a number that doesn't have a leading zero; you could auto-detect such values if they are greater than 4095 (07777 octal):
strnumber = format(number, '5d' if number > 0o07777 else '05o')
and any number with leading zero and the digits 8 or 9 simply fails with a syntax error:
>>> 09876
File "<stdin>", line 1
09876
^
SyntaxError: invalid token
Your better bet is to just enter such numbers as strings instead.

Python, string , integer

I have a string variable:
str1 = '0000120000210000'
I want to convert the string into an integer without losing the first 4 zero characters. In other words, I want the integer variable to also store the first 4 zero digits as part of the integer.
I tried the int() function, but I'm not able to retain the first four digits.
You can use two integers, one to store the width of the number, and the other to store the number itself:
kw = len(s)
k = int(s)
To put the number back together in a string, use format:
print '{:0{width}}'.format(k, width=kw) # prints 0000120000210000
But, in general, you should not store identifiers (such as credit card numbers, student IDs, etc.) as integers, even if they appear to be. Numbers in these contexts should only be used if you need to do arithmetic, and you don't usually do arithmetic with identifiers.
What you want simply cannot be done.. Integer value does not store the leading zero's, because there can be any number of them. So, it can't be said how many to store.
But if you want to print it like that, that can be done by formatting output.
EDIT: -
Added #TimPietzcker's comment from OP to make complete answer: -
You should never store a number as an integer unless you're planning on doing arithmetic with it. In all other cases, they should be stored as strings

Categories

Resources