Basic Types#
Python Numbers#
There are 3 types of numbers in Python - integers, floating-point numbers, and complex numbers.
Number Type | Example | Description |
---|---|---|
Integer | -2, 12389 999999L, ∞ 0b1110, 0xabf, 0o126 | In Python 2, there is a distinction between int and long, with long integers being able to represent infinity In Python 3, they are collectively referred to as int Binary, hexadecimal, and octal representations of integers |
Float | -3.23, -52.3E-4 | Floating-point numbers can be represented in scientific notation in Python |
Complex | -5+4j, 2.3-4.6j | Where -5 and 4 are real numbers, j is the imaginary unit |
-
==int==
In Python 3, there is only int (which can store very large data).
Integer Base Representation Base Representation Method Example Binary Starts with 0b, can only contain 0 and 1, increments by 2 0b11, 0b12 (invalid representation) Octal Starts with 0o, can contain 0-7, increments by 8 0o11 Hexadecimal Starts with 0x, can contain 0-F, increments by 16 0x11 Decimal Composed directly of digits 0-9, increments by 10 11 Integer Base Operations
Base Conversion-bin: Convert any base to binary, takes an int, returns a str Base Conversion-oct: Convert any base to octal, takes an int, returns a str Base Conversion-hex: Convert any base to hexadecimal, takes an int, returns a str Base Conversion-int: Convert any base to decimal, takes an int/str, returns an int
# Example >>> bin(10) # Convert decimal to binary '0b1010' >>> bin(0o71) # Convert octal to binary '0b111001' >>> bin(0x11) # Convert hexadecimal to binary '0b10001' >>> int("10") 10 # Convert str to int >>> int("0o11", base=8) # Octal string, must specify 9 >>> int(0o11) # Directly convert octal int 9
-
==float==
float (floating-point type): A floating-point number is a number with a decimal point.
A float consists of an integer part, a decimal point, and a fractional part, and can also be represented in scientific notation, such as -3.23, -52.3E-4, 6.23E12.
A float is imprecise.
decimal module
Decimal type data is precise decimal numbers and can be passed as a Decimal integer or string parameter.
Official Documentation
float https://docs.python.org/3/library/functions.html#float
decimal https://docs.python.org/3/library/decimal.html?highlight=decimal
# Example: Floating-point data float is imprecise
>>> i = 1
>>> i = i - 0.1
>>> i
0.9
>>> i = i - 0.1
>>> i
0.8
>>> i = i - 0.1
>>> i
0.7000000000000001
>>> i = i - 0.1
>>> i
0.6000000000000001
# Example: Decimal type data is precise decimal numbers and can be passed as a Decimal integer or string parameter
>>> from decimal import getcontext, Decimal, Context
>>> mydec = Decimal.from_float(12.222)
>>> mydec
Decimal('12.2219999999999995310417943983338773250579833984375')
>>> mydec = Decimal(0.9)
>>> mydec
Decimal('0.90000000000000002220446049250313080847263336181640625')
>>> mydec = Decimal("3.14")
>>> mydec
Decimal('3.14')
-
==complex==
Complex numbers: A complex number is a combination of real and imaginary numbers.
In mathematics, the basic form of a complex number is a + bi, where a and b are real numbers, a is called the real part, bi is called the imaginary part, and i is the imaginary unit.
A complex number consists of a real part and an imaginary part, generally represented as x + yj, where x is the real part of the complex number, and y is the imaginary part, both x and y are real numbers.
# Example >>> a = 5 + 4j >>> a.real 5.0 # Stores as float >>> a.imag 4.0
Python Strings#
Strings: A string is a sequence of characters.
Representation methods: single quotes ('), double quotes (“), triple quotes (''' or ”””), raw output.
Symbol | Description | Example |
---|---|---|
Single Quote (') | Can quote strings containing double quotes | 'say“hello”' |
Double Quote (") | Can quote strings containing single quotes | “What's your name?” |
Triple Quote (''' or ”””) | Can quote a multi-line string, can freely use single and double quotes | ''' This is a multi-line character It can contain single quote ' and double quote ” ''' |
Special Mark (r) | Does not escape characters, outputs characters as is | r”hello\tworld!” |
# Example
>>> a = 'test'
>>> b = "test"
>>> a
'test'
>>> b
'test'
>>> a = '''
... t
... e
... s
... t'''
>>> a
'\nt\ne\ns\nt'
>>> print(a)
t
e
s
t
# print(a) prints according to the specified format
>>> c = "t1\nt2"
>>> c
't1\nt2'
>>> print(c)
t1
t2
>>> c = 't1\nt2'
>>> c
't1\nt2'
>>> print(c)
t1
t2
>>> c = r"t1\nt2"
>>> print(c)
t1\nt2
-
==Escape Characters==
Escape characters are a special type of character constant. Escape characters start with a backslash "" followed by one or more characters. Escape characters have specific meanings, different from their original meanings, hence the term "escape" characters.
Escape Character | Description | Escape Character | Description | Escape Character | Description |
---|---|---|---|---|---|
\ (at line end) | Continuation | \n | New line | \oyy | Octal number, yy represents the character, e.g., \o12 represents a new line |
\\ | Backslash | \v | Vertical tab | \xyy | Hexadecimal number, yy represents the character, e.g., \x0a represents a new line |
\' | Single quote | \t | Horizontal tab | \other | Other characters output in normal format |
\" | Double quote | \r | Carriage return | \b | Backspace |
\a | Bell | \f | Form feed | \e | Escape |
\000 | Null |
-
==String Indexing==
Indexing method (note: indexing starts from 0)
Slicing method
# Example
>>> a = "test"
>>> a[0]
't'
>>> a = "test"
>>> a[0:2] # Get data from index 0 to 2. Includes 0, excludes 2
'te' # Includes the front, excludes the back
Strings are immutable sequences.
Once a string is created, it cannot be changed.
# Example
>>> a = "hello world"
>>> a[4] = "1"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> id(a)
140585442705648
Concatenated Strings
If two strings are placed next to each other, Python will automatically concatenate them.
# Example
>>> info = "chen""peng"
>>> info
'chenpeng'
- ==Common String Methods==
- ==Common String Methods - Judgment Series (True/False)==
Method | Function |
---|---|
str.isdigit() | Whether the string contains only digits |
str.isnumeric() | Whether the string contains only digits (including Chinese numbers one to nine, etc.) |
str.isalnum() | Whether the string contains only letters or digits |
str.istitle() | Whether the first letter of each word is capitalized, other letters are lowercase |
str.isalpha() | Whether the string contains only letters (Chinese characters count as letters) |
str.isupper() | Whether the string is all uppercase |
str.isidentifier() | Whether the string is a valid identifier |
str.isprintable() | Whether the string contains printable characters |
str.islower() | Whether the string is all lowercase |
str.isspace() | Whether the string contains only spaces (tab also counts as space) |
str.startswith(prefix[,start[,end]]) | Whether the string starts with a certain string, can set search range with start and stop parameters |
str.endswith(suffix[,start[,end]]) | Whether the string ends with a certain string, can set search range with start and stop parameters |
# Example
my_str = "This Is TEST!"
my_title = "This is My Title"
my_num = "123"
my_num2 = "一二三四"
my_str2 = "hello"
my_str3 = "hello123"
# Judgment Series
print("Is digit:", my_num.isdigit()) # Whether the string contains only digits
print("Is digit:", my_num.isnumeric()) # Whether the string contains only digits (including Chinese numbers one to nine, etc.)
print("Is digit:", my_num2.isdigit()) # Can only judge Arabic numerals
print("Is digit:", my_num2.isnumeric()) # Can judge Chinese numbers
print("Is letter:", my_str.isalpha()) # Will report an error if there are spaces/“!” # Judge letters (Chinese characters count as letters)
print("Is letter or digit:", my_str3.isalnum()) # Will report an error if there are spaces # Judge letters and digits
print("Does the string start with 'This':", my_title.startswith("This"))
print("Does the string end with 'This':", my_title.endswith("This"))
- ==Common String Methods - Search and Count==
Method | Function |
---|---|
len(string) | Count the length of the string |
str.index(sub[,start[,end]]) | Displays the index of the first occurrence of substring in the string, raises an error if not found |
str.find(sub[,start[,end]]) | Searches for substring, returns its starting position if found, returns -1 if not found |
# Example
# Search and Count
my_str = "This Is TEST!"
print("Length:", len(my_str)) # Spaces and ! count as length
print("Position of 'i' first occurrence:", my_str.index("i")) # Position of the first occurrence of the string "i"
print("Position of 'i' first occurrence:", my_str.find("i")) # Position of the first occurrence of the string "i", returns -1 if not found
print("Number of occurrences of 'i':", my_str.count("i"))
- ==Common String Methods - String Conversion (Returns a new object)==
Method | Function |
---|---|
str.upper() | Convert the string to uppercase |
str.lower() | Convert the string to lowercase |
str.title() | Capitalize the first letter of each word in the string, other letters lowercase |
str.split('sep') | Split the string into a list using 'sep' as the separator, the separator can be any character (default is space) |
'str'.join(list) | Join the list into a large string using str |
str.strip([string]) | Remove the leading and trailing characters from the string, defaults to removing spaces if no parameter is provided |
str.zfill(number) | Return a string of specified length, right-aligns the original string, fills with 0 in front |
str.replace('old','new'[,count]) | Replace old characters with new characters, can also specify the number of replacements, defaults to replacing all |
str.capitalize() | Capitalize the first letter of the sentence |
str.center(width[,fillchar]) str.ljust(width[,fillchar]) str.rjust(width[,fillchar]) | Return the original string centered (left/right aligned), width is the total length, filled with a character fillchar on both sides, if the specified length is less than the original string length, return the original string |
str.expandtabs(number) | Convert \t to number spaces |
# Example
# String Conversion
msg = " hEllo World Chen "
print("Uppercase:", msg.upper())
print("Lowercase:", msg.lower())
print("Title:", msg.title())
msg2 = "root:x:0:0:root:/root:/bin/bash"
print("Split:", msg2.split(":"))
msg3 = msg2.split(":")
print("Join:", "#".join(msg3))
print("Trim leading and trailing spaces:", msg.strip(), "######")
print("Trim 'root' from both ends:", msg2.strip("root"))
print("String padding:", msg.zfill(40))
print("String replacement:", msg2.replace(":", "%"))
print("Capitalize the first letter of the entire string:", msg.capitalize())
msg4 = "xxx"
print(msg4.center(50, ' '))
print(msg4.center(50, '-'))
print(msg4.ljust(50, "-"))
print(msg4.rjust(50, "-"))
- ==String Concatenation==
# Example
# String concatenation (+)
>>> a = 'I' + 'Love' + 'Python'
>>> print(a)
ILovePython
# String concatenation (join)
>>> a = ['I', 'Love', 'Python']
>>> print(''.join(a))
ILovePython
+ and join efficiency issue
Generally, + concatenation is less efficient than join concatenation.
With + concatenation, a new space is allocated in memory each time it appears, so it is less efficient and takes more time.
join concatenates into one large string at once.
- ==String Formatting==
String formatting (%)
Basic format
%[(name)][flags][width].[precision]typecode
-(name): naming
-flags: +, -, '' or 0. + indicates right alignment; - indicates left alignment; '' is a space, indicating filling a space on the left side of positive numbers to align with negative numbers, 0 indicates filling with 0.
-width indicates display width.
-precision indicates precision after the decimal point.
# Example
# % formatting
name = "wen"
age = 18
print("Name: %s, Age: %s" % (name, age))
print("Name: %s, Age: %s" % (age, "wen2"))
String formatting (format)
{variable:[filling character][alignment <^>][width][format]}
# Example
# format formatting
name = "wen"
age = 18
print("format01 --> Name: {}, Age: {}".format(name, age))
print("format01 --> Name: {}, Age: {}".format(age, name))
print("format02 --> Name: {1}, Age: {0}".format(name, age))
print("format02 --> Name: {1}, Age: {0}".format(age, name))
print("format03 --> Name: {name1}, Age: {age1}".format(name1=name, age1=age))
print("format01 --> {0:*>10}".format(10, 20)) # Note: 0 is the first variable
print("format01 --> {1:*>10}".format(10, 20)) # Note: 1 is the second variable
print("format01 --> {1:*<10}".format(10, 20)) # Note: : execution; * is the filling character
print("format01 --> {1:*^10}".format(10, 20)) # Note: ^ is centered; 10 is the filling width of 10 characters
print("format02 --> {0:.2f}".format(1/3, 5.333))
print("format02 --> {1:06.2f}".format(1/3, 5.333))
# Binary
print("format02 --> {0:b}".format(10))
# Octal Note: Hexadecimal is "{0:x}".format(10)
print("format02 --> {0:o}".format(10))
# Thousands separator formatting
print("format02 --> {0:,}".format(123456789))
String formatting - f
# Example
# f identifier formatting
a = "I"
b = "Love"
c = "Python"
print(f"{a}{b}{c}")
# Result ILovePython
print("{a}{b}{c}".format(a=a, b=b, c=c)) # Note: Effect is the same
# Result ILovePython
print(f"{a}{b}{c:a^10}") # Note: Operation on string c: fill width 10 with “a”, centered
# Result ILoveaaPythonaa
print("{a}{b}{c:a^10}".format(a=a, b=b, c=c)) # Note: Effect is the same
# Result ILoveaaPythonaa
Python Numbers - Booleans#
Boolean values (Booleans) are logical values.
The range of values is only True and False (true and false).
False boolean values:
'', 0, 0.0, (), [], {}, None, False
None is a special constant representing a special data type (NoneType).
True boolean values:
All values except false are true.
# Example
# Boolean values can be added and subtracted
>>> a = 1
>>> b = 2
>>> print(a == b)
False
>>> c = (a == b) + (a == d) # Note: c = 0 + 1
>>> c
1
# Boolean sorting
>>> lst = [(a == d), (a == b)] # Note: (a == d) is true, (a == b) is false
>>> sorted(lst)
[False, True] # Note: Because by default 0 is false, 1 is true
Others#
○ Constants
A constant is a fixed value that cannot be changed once initialized.
Note: In Python, a constant is usually represented in uppercase (by convention, not mandatory), such as: PI=3.1415926.
○ NoneType
None represents the absence of value.