How also to use int() and format() functions in Python
2 min readAug 25, 2022
The aim of this pageš is to provide examples of usage of built-in functions int()
and format()
used in the primitive one-liner solution of https://leetcode.com/problems/add-binary/solution/. A more general lesson is that apart from learning algorithms, it is good to solve puzzles with the built-in functions and study them to learn the used language.
1. CODE
def ab(a,b):
return format((int(a,2) + int(b,2)),"b")
2. int()
- usually used for the casting of string into integer
- but can be used for base conversion, too, with the second, optional
base
argument
class int(x, base=10)
- the allowed values for the base are 0 and 2ā36.
BASE | PREFIX | MEANING
-----|--------|--------
2 | 0b/0B | binary
8 | 0o/0O | octal
16 | 0x/0X | hex
- these correspond to integer literals in code
3. format()
- there is a Format Specification Mini-Language aka format specs in python
- format specs are used within replacement fields
- replacement fields are substrings of a format string
>>> bin(108)
'0b1101100'
--*******
--*******: formt string
--: replacement fields
- format specs defined how replacement fields are presented
- the format function takes two arguments
format(value[, format_spec])
- In
format((int(a,2) + int(b,2)),"b")
ā¦"b"
specifies that the passed value is a binary
format()
converts the integer into a binary integer literal without0b
prefix- I find this more elegant than using
bin()
with slicing
format(int("108"), "b")
>>> '1101100'
bin(108)[2:]
>>> '1101100'