Python Convert a String of Numbers to Binary Representation

Document 对象参考手册Python3 Examples

In Python, we can use the built-inbin()function that converts an integer to a binary string. This function returns a string starting with "0b", indicating that this is a binary number.

Example

# Define an integer
number = 42

# Use the bin() function to convert it to a binary string
binary_representation = bin(number)

# Print the result
print(binary_representation)

Code analysis:

  1. number = 42: Define an integer variablenumber, with a value of 42.
  2. binary_representation = bin(number): Usebin()the function to convert the integernumberto a binary string, and the result is stored inbinary_representationthe variable.
  3. print(binary_representation): Print the binary string.

Output result:

0b101010

Document 对象参考手册Python3 Examples

Other extensions