Strings and Number Systems
Understanding the Relationship
While strings and number systems might seem unrelated at first, they are interconnected in Python through data type conversions.
Strings are sequences of characters, representing textual information. They can contain numbers, but they are treated as characters, not numerical values.
Number systems are ways to represent numerical values. Python primarily supports the decimal (base 10) system, but it also allows for binary (base 2), octal (base 8), and hexadecimal (base 16) representations.
Conversion Between Strings and Numbers
Python provides built-in functions to convert between strings and numeric data types:
1. Converting Strings to Numbers:
·
int()
: Converts a string to an
integer. The string must represent a whole number.
·
float()
: Converts a string to a
floating-point number. The string can contain a decimal point.
·
complex()
: Converts a string to a
complex number. The string must be in the form real+imaginaryj
.
Python
string_number =
"42"
integer_value =
int(string_number)
print(integer_value)
# Output: 42
float_value =
float(
"3.14")
print(float_value)
# Output: 3.14
complex_value =
complex(
"2+3j")
print(complex_value)
# Output: (2+3j)
2. Converting Numbers to Strings:
·
str()
: Converts a number to a
string.
Python
number =
42
string_value =
str(number)
print(string_value)
# Output: "42"
Number Systems in Python
Python supports various number systems through string representations:
·
Binary: Preceded by 0b
or 0B
.
Python
binary_number =
0b1010
# Equivalent to decimal 10
·
Octal: Preceded by 0o
or 0O
.
Python
octal_number =
0o75
# Equivalent to decimal 61
·
Hexadecimal: Preceded by 0x
or 0X
.
Python
hexadecimal_number =
0xFF
# Equivalent to decimal 255
Converting Between Number Systems
You can convert between different number systems using built-in functions:
·
bin()
: Converts an integer to a
binary string.
·
oct()
: Converts an integer to an
octal string.
·
hex()
: Converts an integer to a
hexadecimal string.
Python
decimal_number =
42
binary_string =
bin(decimal_number)
# Output: '0b101010'
octal_string =
oct(decimal_number)
# Output: '0o52'
hexadecimal_string =
hex(decimal_number)
# Output: '0x2a'
By understanding the relationship between strings and number systems, you can effectively manipulate and convert data in your Python programs.