- Python: 3 Ways to Convert a String to Binary Codes
- Using the ord() function and string formatting
- Using the bytearray() function
- Using the bin() and ord() functions
- Conclusion
- Python print bin string
- # Table of Contents
- # Print the binary representation of a Number in Python
- # Print the binary representation of a Number using bin()
- # Convert the integer to an uppercase or lowercase hexadecimal string
- # Convert an integer to binary and keep leading zeros — Python
- # Convert an integer to binary and keep leading zeros using f-string
- # Convert an integer to binary and keep leading zeros using str.format()
- # Additional Resources
- Функция bin() в Python
- С целыми числами другого формата
- С аргументом float
- С объектом
Python: 3 Ways to Convert a String to Binary Codes
Binary codes (binary, binary numbers, or binary literals) are a way of representing information using only two symbols: 0 and 1. They are like a secret language that computers are able to understand. By combining these symbols in different patterns, we can represent numbers, letters, and other data.
This concise, example-based article will walk you through 3 different approaches to turning a given string into binary in Python.
Using the ord() function and string formatting
- Loop through each character in the string.
- Convert each character to its corresponding Unicode code using the ord() function.
- Convert the Unicode code to binary using the format() function with a format specifier.
- Concatenate the binary codes to form the final binary string.
input = "Sling Academy" binary_codes = ' '.join(format(ord(c), 'b') for c in input) print(binary_codes)
1010011 1101100 1101001 1101110 1100111 100000 1000001 1100011 1100001 1100100 1100101 1101101 1111001
Using the bytearray() function
- Convert the string to a bytearray object, which represents the string as a sequence of bytes.
- Iterate over each byte in the bytearray.
- Convert each byte to binary using the format() function with a format specifier.
- Concatenate the binary codes to form the final binary string.
my_string = "Sling Academy" byte_array = bytearray(my_string, encoding='utf-8') binary_codes = ' '.join(bin(b)[2:] for b in byte_array) print(binary_codes)
1010011 1101100 1101001 1101110 1100111 100000 1000001 1100011 1100001 1100100 1100101 1101101 1111001
Using the bin() and ord() functions
This technique can be explained as follows:
- Iterate over each character in the string.
- Convert each character to its corresponding Unicode code using the ord() function.
- Use the bin() function to convert the Unicode code to binary.
- Remove the leading 0b prefix from each binary code.
- Concatenate the binary codes to form the final binary string.
Thanks to Python’s concise syntax, our code is very succinct:
text = "Sling Academy" binary_string = ' '.join(bin(ord(char))[2:] for char in text) print(binary_string)
1010011 1101100 1101001 1101110 1100111 100000 1000001 1100011 1100001 1100100 1100101 1101101 1111001
Conclusion
You’ve learned some methods to transform a given string into binary in Python. All of them are neat and delicate. Choose the one you like to go with. Happy coding & have a nice day!
Python print bin string
Last updated: Jan 28, 2023
Reading time · 4 min
# Table of Contents
# Print the binary representation of a Number in Python
Use a formatted string literal to print the binary representation of a number, e.g. print(f») .
Formatted string literals enable us to use the format specification mini-language which can be used to get the binary representation of a number.
Copied!number = 13 # ✅ format number as binary (in base 2) string = f'number:b>' print(string) # 👉️ 1101 # ✅ Convert an integer to a binary string prefixed with 0b string = bin(number) print(string) # 👉️ 0b1101 # ✅ convert an integer to a lowercase hexadecimal string prefixed with 0x string = hex(number) print(string) # 👉️ 0xd
Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f .
Copied!var1 = 'bobby' var2 = 'hadz' result = f'var1>var2>' print(result) # 👉️ bobbyhadz
Make sure to wrap expressions in curly braces — .
Formatted string literals also enable us to use the format specification mini-language in expression blocks.
Copied!number = 13 string = f'number:b>' print(string) # 👉️ 1101
The b character stands for binary format and outputs the number in base 2.
You can prefix the b character with a digit to specify the width of the string.
Copied!number = 13 string = f'number:8b>' print(repr(string)) # 👉️ ' 1101'
If you need to pad the number with zeros instead of spaces, add a zero after the colon.
Copied!number = 13 string = f'number:08b>' print(repr(string)) # 👉️ '00001101'
You can also prefix the result with 0b if necessary.
Copied!number = 13 string = f'0bnumber:08b>' print(repr(string)) # 👉️ '0b00001101'
# Print the binary representation of a Number using bin()
Alternatively, you can use the bin() function.
Copied!number = 13 string = bin(number) print(string) # 👉️ 0b1101 print(bin(3)) # 👉️ 0b11 print(bin(10)) # 👉️ 0b1010
The bin function converts an integer to a binary string prefixed with 0b .
You can also use a formatted string literal to add or remove the 0b prefix.
Copied!number = 13 string = f'number:#b>' print(string) # 👉️ 0b1101 string = f'number:b>' print(string) # 👉️ 1101
When used with integers, the # option adds the respective prefix to the binary, octal or hexadecimal output, e.g. 0b , 0o , 0x .
If you need to get the hexadecimal representation of a number, use the hex() function.
Copied!number = 13 string = hex(number) print(string) # 👉️ 0xd
The hex function converts an integer to a lowercase hexadecimal string prefixed with 0x .
# Convert the integer to an uppercase or lowercase hexadecimal string
You can also use a formatted string literal to convert an integer to an uppercase or lowercase hexadecimal string with or without the prefix.
Copied!number = 13 string = f'number:#x>' print(string) # 👉️ 0xd string = f'number:x>' print(string) # 👉️ d string = f'number:X>' print(string) # 👉️ D
The x character stands for hex format. It outputs the number in base 16 using lowercase letters for the digits above 9.
The X character does the same but uses uppercase letters for the digits above 9.
# Convert an integer to binary and keep leading zeros — Python
Use the format() function to convert an integer to binary and keep the leading zeros.
Copied!integer = 27 # ✅ convert integer to binary keeping leading zeros (with 0b prefix) result = format(integer, '#08b') print(result) # 👉️ 0b011011 # ✅ without 0b prefix (length 6) result = format(integer, '06b') print(result) # 👉️ 011011
We used the format function to convert an integer to binary and keep the leading zeros.
The function converts the provided value to a formatted representation according to the format_spec argument.
The syntax for the format_spec argument is determined by the format specification mini-language.
When used with integers, the # option adds the respective prefix to the binary, octal or hexadecimal output, e.g. 0b , 0o , 0x .
Copied!integer = 27 result = format(integer, '#08b') print(result) # 👉️ 0b011011
If you don’t need the 0b prefix, remove the # option.
Copied!integer = 27 result = format(integer, '06b') print(result) # 👉️ 011011
The 0 digit is the fill character and the digit after the 0 is the width of the string.
The b character stands for binary format and outputs the number in base 2.
You can prefix the b character with any digit to adjust the width of the string.
Copied!integer = 27 result = format(integer, '#010b') print(result) # 👉️ 0b00011011 result = format(integer, '08b') print(result) # 👉️ 00011011
# Convert an integer to binary and keep leading zeros using f-string
Alternatively, you can use a formatted string literal.
Copied!integer = 27 # ✅ with 0b prefix (length 8) result = f'integer:#08b>' print(result) # 👉️ 0b011011 # ✅ without 0b prefix (length 6) result = f'integer:06b>' print(result) # 👉️ 011011
Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f .
Copied!var1 = 'bobby' var2 = 'hadz' result = f'var1>var2>' print(result) # 👉️ bobbyhadz
Make sure to wrap expressions in curly braces — .
Formatted string literals also enable us to use the format specification mini-language in expression blocks.
Copied!integer = 27 result = f'integer:#08b>' print(result) # 👉️ 0b011011
Just like with the format function, the b character stands for binary format.
If you need to remove the 0b prefix, remove the # symbol.
Copied!integer = 27 result = f'integer:06b>' print(result) # 👉️ 011011
If you need to change the width of the string, adjust the digit before the b character.
Copied!integer = 27 result = f'integer:010b>' print(result) # 👉️ 0000011011
The number is formatted in base 2, left-filled with zeros to the specified width.
# Convert an integer to binary and keep leading zeros using str.format()
Alternatively, you can use the str.format() method.
Copied!integer = 27 result = ''.format(integer) print(result) # 👉️ 0b011011 result = ''.format(integer) print(result) # 👉️ 011011
The str.format method performs string formatting operations.
Copied!first = 'Bobby' last = 'Hadz' result = "His name is <> <>".format(first, last) print(result) # 👉️ "His name is Bobby Hadz"
The string the method is called on can contain replacement fields specified using curly braces <> .
The str.format() method also makes use of the format specification mini-language, so we used the same syntax as in the previous examples.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
Функция bin() в Python
Функция bin() в Python используется для преобразования целого числа в строку двоичного формата. Форматированная строка имеет префикс «0b».
Функция bin() может использоваться с целыми числами, имеющими разные форматы, такие как восьмеричный, шестнадцатеричный. Функция позаботится о преобразовании их в двоичную строку. Давайте посмотрим на несколько примеров функции bin().
x = 10 y = bin(x) print(type(y)) print(bin(x))
Из вывода видно, что функция bin() возвращает строку, а не число. Функция ype() возвращает тип объекта.
С целыми числами другого формата
Давайте посмотрим на несколько примеров использования функции bin() с целыми числами в разных форматах.
x = 0b110 # 6 print(bin(x)) x = 0xF # 15 print(bin(x)) x = 0o70 # 56 print(bin(x))
Совет: Если вам не нужен префикс «0b» в двоичной строке, вы также можете использовать функцию format(). Вот быстрый пример, показывающий, как использовать функцию format().
x = 10 print(format(x, '#b')) # 0b1010 print(format(x, 'b')) # 1010 x= 0xF print(format(x, 'b')) # 1111 print(f'') # 1111 (If you knew this format, you are Python Ninja!)
С аргументом float
Давайте посмотрим, что произойдет, когда мы попытаемся запустить функцию bin() с аргументом float.
TypeError: 'float' object cannot be interpreted as an integer
С объектом
Если вы хотите иметь двоичное строковое представление объекта, вам нужно будет реализовать функцию __index __(), которая должна возвращать целое число. Давайте посмотрим на простом примере.
class Person: def __init__(self, i): self.id = i def __index__(self): return self.id p = Person(10) print(bin(p))
Если объект не определяет функцию __index __(), мы получим сообщение об ошибке, как TypeError: объект ‘Person’ не может быть интерпретирован как целое число.
Посмотрим, что произойдет, если функция __index __() вернет no-int. Просто измените функцию index() на следующую:
def __index__(self): return str(self.id)
Ошибка: TypeError: __index__ вернул no-int (тип str).
Это все, что касается функции bin() для преобразования целого числа в двоичную строку. Мы также узнали, что объект также можно преобразовать в двоичное строковое представление, реализовав функцию __index __(), которая возвращает целое число.