- Type Related Functions
- Numeric Types
- Common Numeric Types
- Arithmetic Operators
- Functions
- Related Modules
- Integer Sequence - Range
- Text Sequence - Strings
- Literals
- Escape Characters
- Length
- String Operators
- String Interpolation
- Methods
- Special Prefixes
- Unicode code point
- Boolean Type
- Boolean Values
- Comparison Operators
- Boolean Operators
- Operator Precedence
- None Type
- Union Type
The function type(variable) returns the data type of any variable.
The type names are also function names (int(), float(), str(), etc.) that usually converts other type of data to the specified type.
The typing module provides runtime support for type hints.
from typing import Any, Union, Optional, Callable, Generic, TypeVar, TypeAlias
Number = Union[int, float]
NullString = Optional[str]
Factors: TypeAlias = list[int]Integer - Whole number. By default decimal; 0b prefix for binary; 0o prefix for octal; 0x prefix for hexadecimal.
Floating-Point Number - Number with a decimal point or using scientific notation (with an e sign).
Complex Number - Number in form of a + bj where a and b are integers or floats. z.real and z.imag indicates corresponding parts.
| Operators | Descriptions |
|---|---|
+ |
Addition |
- |
Subtraction |
* |
Multiplication |
** |
Power |
/ |
Division |
// |
Floor Division |
% |
Modulo |
The precedence of the arithmetic operators is coherent with that in math.
pow(x, y)returnsxto the powery.abs(x)returns absolute value or magnitude ofx.round(x, n=0)returnsxrounded tondigits, rounding half to even.
mathprovides access to the mathematical functions defined by the C standard; cannot be used with complex numbers.cmathprovides access to mathematical functions for complex numbers; will accept all common numeric types.
Range is a special type of data which is an immutable sequence of integers generated by the range(start=0, stop, step=1) function. For a non-zero step, the sequence are determined by the formula
r[i] = start + step*i where i >= 0 and r[i] < stop for a positive step, i >= 0 and r[i] > stop for a negative step.
A single line string begins and ends with a single quote or double quote.
A multiline string begins and ends with three single quotes or double quotes. Use \ at the end of a line to indicate line continuation.
An escape character consists of a backslash \ followed by a character indicates what to add to the string.
| Syntax | Descriptions |
|---|---|
\' |
Single Quote |
\" |
Double Quote |
\\ |
Backslash |
\n |
Line Feed |
\r |
Carriage Return |
\t |
Tabulation |
\v |
Line Tabulation |
\f |
Form Feed |
\a |
Bell |
\b |
Backspace |
\o |
Octal Value |
\x |
Hex Value |
\0 |
Null Character |
Despite consisting of two characters, it is commonly referred to as a singular escape character.
len(string) returns the number of characters in the string in form of an integer.
| Operators | Descriptions |
|---|---|
+ |
Concatenation |
* |
Repetition |
[] |
Slicing |
in |
Membership |
not in |
Negated Membership |
Use the string % (variable1, variable2, ..., variableN) syntax to format a string, i.e. to insert values in the tuple to the string.
| Placeholders | Descriptions |
|---|---|
%d |
Signed decimal integer |
%u |
Unsigned decimal integer |
%f |
Floating-point real number |
%c |
Single character |
%s |
String |
Adding a number before the letter indicates the total space that shall be reserved. By default, the content of the placehold aligns right, but a minus sign switch it to align left.
Letter Case
string.upper()returns a string with all letters converted to upper case.string.lower()returns a string with all letters converted to lower case.string.title()returns a titlecased string, i.e. with first letter of each word capitalized.string.isupper()checks if the string contains at least 1 letter and all letters are uppercased.string.islower()checks if the string contains at least 1 letter and all letters are lowercased.string.istitle()checks if the string contains at least 1 letter and all letters are properly titlecased, i.e. with first letter of each word capitalized.
Character Categories
string.isalpha()checks if the string is not empty and has only letters.string.isalnum()checks if the string is not empty and has only letters and numbers.string.isdecimal()checks if the string is not empty and has only numbers.string.isspace()checks if the string is not empty and has only whitespace.string.isidentifier()checks if the string is a valid identifier in Python.
Affix
string.startswith('prefix')checks if the string starts with the prefix string.string.endswith('suffix')checks if the string ends with the suffix string.
Separation
string.split(separator=' ')splits a string to a list of strings according to the separator string, with the separator omiited.separator.join([string1, string2, ..., stringN])joins a list or tuple of strings to one string with the separator string added between each two.
Partition
string.partition(separator)searches from the left, and partitions the string into 3 parts: the text before it, the separator itself and the text after it.string.rpartition(separator)searches from the right, and partitions the string into 3 parts: the text before it, the separator itself and the text after it.
Search and Replacement
string.find(substring)returns the index of first occurrence of the substring, or -1 if not found.string.rfind(substring)returns the index of last occurrence of the substring, or -1 if not found.string.replace(substring, repl)returns the string with each matching occurrence of the substring replaced by the replacement string.
Strip
string.strip(chars)strips out any character in the chars string (whitespace if omitted) from both sides of the string.string.lstrip(chars)strips out any character in the chars string (whitespace if omitted) from the left side of the string.string.rstrip(chars)strips out any character in the chars string (whitespace if omitted) from the right side of the string.
Alignment
string.center(width, padding)center aligns the string to a specified width using the padding character (' 'if omitted) as the fill.string.ljust(width, padding)left aligns the string to a specified width using the padding character (' 'if omitted) as the fill.string.rjust(width, padding)right aligns the string to a specified width using the padding character (' 'if omitted) as the fill.
Formatting
string.format(variable1, variable2, ..., variableN) formats the specified values and insert them inside the string's placeholder.
The placeholder is defined by curly brackets {} that hold:
- An index number (starting from 0) that maps to positional parameters or a keyword that maps to keyword parameters;
- Optional
:followed by the type characters which together specify the formatting type.
| Type Character | Descriptions |
|---|---|
< |
Left align to the remaining space |
> |
Right align to the remaining space |
^ |
Center align to the remaining space |
= |
Force the plus/minus sign to the leftmost position |
, |
Use commas as thousand separators |
_ |
Use underscores as thousand separators |
+ |
Add a plus sign to positive numbers |
d |
Decimal integer |
b |
Binary format |
o |
Octal format |
x |
Hexadecimal format |
X |
Hexadecimal format (upper case) |
e |
Scientific notation |
E |
Scientific notation (uppercase E) |
f |
Fixed point number |
F |
Fixed point number (uppercase INF and NAN) |
g |
General format - the shorter version of f and e |
G |
General format (uppercase E) |
% |
Percentage format |
c |
Corresponding Unicode character |
Raw Strings
Place an r before the beginning quotation mark of a string to make it a raw string.
A raw string completely ignores all escape characters and prints any backslash that appears in the string.
Formatted Strings
Formatted strings have an f prefix before the starting quotation mark.
The expressions placed directly inside the braces will be evaluated and interpolated in the string.
- The
ord()function gets the code point of a one-character string; - The
chr()function gets the one-character string of an integer code point.
Boolean data type has only two values: True and False.
| Operators | Descriptions |
|---|---|
== |
Equal to |
!= |
Not equal to |
< |
Less than |
> |
Greater than |
<= |
Less than or equal to |
>= |
Greater than or equal to |
is |
Object identity (memory address) |
is not |
Negated object identity |
in |
Membership |
not in |
Negated Membership |
and- Intersection. A series of values connected byandreturns the first value evaluatedFalseor the last value.or- Union. A series of values connected byorreturns the first value evaluatedTrueor the last value.not- Complement.
From high to low:
- Arithmetic operators;
- Comparison operators;
- Identity or membership operators;
- Unary logical operator;
- Binary logical operators (
andhigher thanor).
None data type has only one value: None, representing the null value or the null object. It is commonly returned by functions that do not explicitly return a value.
A union object holds the value of the bitwise or | operation on multiple type objects, and creates a Union Type.
| Type Hints | Shorthand Syntax |
|---|---|
typing.Union[X, Y] |
X | Y |
typing.Optional[X] |
X | None |
Sweigart, A. (2015). Automate the Boring Stuff With Python: Practical Programming for Total Beginners. San Francisco, CA: No Starch Press.