Skip to content

Latest commit

 

History

History
316 lines (219 loc) · 11.4 KB

File metadata and controls

316 lines (219 loc) · 11.4 KB

Python Data Types

Table of Contents

Type Related Functions

Type Retrieval

The function type(variable) returns the data type of any variable.

Type Conversion

The type names are also function names (int(), float(), str(), etc.) that usually converts other type of data to the specified type.

Type Hints

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]

Numeric Types

Common Numeric Types

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.

Arithmetic Operators

Operators Descriptions
+ Addition
- Subtraction
* Multiplication
** Power
/ Division
// Floor Division
% Modulo

The precedence of the arithmetic operators is coherent with that in math.

Functions

  1. pow(x, y) returns x to the power y.
  2. abs(x) returns absolute value or magnitude of x.
  3. round(x, n=0) returns x rounded to n digits, rounding half to even.

Related Modules

  1. math provides access to the mathematical functions defined by the C standard; cannot be used with complex numbers.
  2. cmath provides access to mathematical functions for complex numbers; will accept all common numeric types.

Range

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.

Strings

Literals

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.

Escape Characters

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.

Length

len(string) returns the number of characters in the string in form of an integer.

String Operators

Operators Descriptions
+ Concatenation
* Repetition
[] Slicing
in Membership
not in Negated Membership

String Interpolation

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.

Methods

Letter Case

  1. string.upper() returns a string with all letters converted to upper case.
  2. string.lower() returns a string with all letters converted to lower case.
  3. string.title() returns a titlecased string, i.e. with first letter of each word capitalized.
  4. string.isupper() checks if the string contains at least 1 letter and all letters are uppercased.
  5. string.islower() checks if the string contains at least 1 letter and all letters are lowercased.
  6. 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

  1. string.isalpha() checks if the string is not empty and has only letters.
  2. string.isalnum() checks if the string is not empty and has only letters and numbers.
  3. string.isdecimal() checks if the string is not empty and has only numbers.
  4. string.isspace() checks if the string is not empty and has only whitespace.
  5. string.isidentifier() checks if the string is a valid identifier in Python.

Affix

  1. string.startswith('prefix') checks if the string starts with the prefix string.
  2. string.endswith('suffix') checks if the string ends with the suffix string.

Separation

  1. string.split(separator=' ') splits a string to a list of strings according to the separator string, with the separator omiited.
  2. separator.join([string1, string2, ..., stringN]) joins a list or tuple of strings to one string with the separator string added between each two.

Partition

  1. 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.
  2. 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

  1. string.find(substring) returns the index of first occurrence of the substring, or -1 if not found.
  2. string.rfind(substring) returns the index of last occurrence of the substring, or -1 if not found.
  3. string.replace(substring, repl) returns the string with each matching occurrence of the substring replaced by the replacement string.

Strip

  1. string.strip(chars) strips out any character in the chars string (whitespace if omitted) from both sides of the string.
  2. string.lstrip(chars) strips out any character in the chars string (whitespace if omitted) from the left side of the string.
  3. string.rstrip(chars) strips out any character in the chars string (whitespace if omitted) from the right side of the string.

Alignment

  1. string.center(width, padding) center aligns the string to a specified width using the padding character (' ' if omitted) as the fill.
  2. string.ljust(width, padding) left aligns the string to a specified width using the padding character (' ' if omitted) as the fill.
  3. 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

Special Prefixes

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.

Unicode Code Point

  • 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 Type

Boolean Values

Boolean data type has only two values: True and False.

Relational Operators

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

Boolean Operators

  • and - Intersection. A series of values connected by and returns the first value evaluated False or the last value.
  • or - Union. A series of values connected by or returns the first value evaluated True or the last value.
  • not - Complement.

Operator Precedence

From high to low:

  1. Arithmetic operators;
  2. Comparison operators;
  3. Identity or membership operators;
  4. Unary logical operator;
  5. Binary logical operators (and higher than or).

None Type

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.

Union Type

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

References

Sweigart, A. (2015). Automate the Boring Stuff With Python: Practical Programming for Total Beginners. San Francisco, CA: No Starch Press.