List of built-in exceptions in Python 3.
Base Classes
These exceptions are generally used as base classes for other exceptions.
Exception | Description |
---|---|
BaseException | The base class for all built-in exceptions. It is not meant to be directly inherited by user-defined classes (for that, use Exception below). |
Exception | All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from this class. |
ArithmeticError | The base class for built-in exceptions that are raised for various arithmetic errors. These are: OverflowError , ZeroDivisionError , FloatingPointError . |
BufferError | Raised when a buffer related operation cannot be performed. |
LookupError | The base class for exceptions that are raised when a key or index used on a mapping or sequence is invalid. These are: IndexError and KeyError . |
Concrete Exceptions
These are the exceptions that are usually raised.
Exception | Description |
---|---|
AssertionError | Raised when an assert statement fails. |
AttributeError | Raised when an attribute reference or assignment fails. |
EOFError | Raised when the input() function hits an end-of-file condition (EOF) without reading any data. |
FloatingPointError | Raised when a floating point operation fails. |
GeneratorExit | Raised when a generator or coroutine is closed. Technically, this is not an error, and the GeneratorExit exception directly inherits from BaseException instead of Exception . |
ImportError | Raised when the import statement fails when trying to load a module. This exception is also raised when the from in from ... import has a name that cannot be found. |
ModuleNotFoundError | A subclass of ImportError which is raised by import when a module could not be located. This exception is also raised when None is found in sys.modules . |
IndexError | Raised when a sequence subscript is out of range. |
KeyError | Raised when a mapping (dictionary) key is not found in the set of existing keys. |
KeyboardInterrupt | Raised when the user hits the interrupt key (typically Control-C or Delete ). |
MemoryError | Raised when an operation runs out of memory but the situation may still be rescued (by deleting some objects). |
NameError | Raised when a local or global name is not found. This applies only to unqualified names. |
NotImplementedError | This exception is derived from RuntimeError . In user defined base classes, abstract methods should raise this exception when they require derived classes to override the method, or while the class is being developed to indicate that the real implementation still needs to be added. |
OSError() | This exception is raised when a system function returns a system-related error, including I/O failures such as "file not found" or "disk full". |
OverflowError | Raised when the result of an arithmetic operation is too large to be represented. |
RecursionError | This exception is derived from RuntimeError . It is raised when the interpreter detects that the maximum recursion depth is exceeded. |
ReferenceError | Raised when a weak reference proxy, created by the weakref.proxy() function, is used to access an attribute of the referent after it has been garbage collected. |
RuntimeError | Raised when an error is detected that doesn̢۪t fall in any of the other categories. |
StopIteration | Raised by the next() function and an iterator's __next__() method to signal that there are no further items produced by the iterator. |
StopAsyncIteration | Must be raised by __anext__() method of an asynchronous iterator object to stop the iteration. |
SyntaxError | Raised when the parser encounters a syntax error. |
IndentationError | Base class for syntax errors related to incorrect indentation. This is a subclass of SyntaxError . |
TabError | Raised when indentation contains an inconsistent use of tabs and spaces. This is a subclass of IndentationError . |
SystemError | Raised when the interpreter finds an internal error, but it's not serious enough to exit the interpreter. |
SystemExit | This exception is raised by the sys.exit() function, and (when it is not handled) causes the Python interpreter to exit. |
TypeError | Raised when an operation or function is applied to an object of inappropriate type. |
UnboundLocalError | Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable. This is a subclass of NameError . |
UnicodeError | Raised when a Unicode-related encoding or decoding error occurs. It is a subclass of ValueError . |
UnicodeEncodeError | Raised when a Unicode-related error occurs during encoding. It is a subclass of UnicodeError . |
UnicodeDecodeError | Raised when a Unicode-related error occurs during encoding. It is a subclass of UnicodeError . |
UnicodeTranslateError | Raised when a Unicode-related error occurs during encoding. It is a subclass of UnicodeError . |
ValueError | Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception. |
ZeroDivisionError | Raised when the second argument of a division or modulo operation is zero. |
OS Exceptions
These exceptions are subclasses of OSError
. They get raised depending on the actual system error code.
Exception | Description |
---|---|
BlockingIOError | Raised when an operation would block on an object (e.g. socket) set for non-blocking operation. |
ChildProcessError | Raised when an operation on a child process failed. |
ConnectionError | A base class for connection-related issues. |
BrokenPipeError | A subclass of ConnectionError , raised when trying to write on a pipe while the other end has been closed, or trying to write on a socket which has been shutdown for writing. |
ConnectionAbortedError | A subclass of ConnectionError , raised when a connection attempt is aborted by the peer. |
ConnectionRefusedError | A subclass of ConnectionError , raised when a connection is reset by the peer. |
FileExistsError | Raised when trying to create a file or directory which already exists. |
FileNotFoundError | Raised when a file or directory is requested but doesn̢۪t exist. |
InterruptedError | Raised when a system call is interrupted by an incoming signal. |
IsADirectoryError | Raised when a file operation is requested on a directory. |
NotADirectoryError | Raised when a directory operation is requested on something which is not a directory. |
PermissionError | Raised when trying to run an operation without the adequate access rights. |
ProcessLookupError | Raised when a given process doesn̢۪t exist. |
TimeoutError | Raised when a system function timed out at the system level. |
Warnings
The following exceptions are used as warning categories.
Exception | Description |
---|---|
Warning | Base class for warning categories. |
UserWarning | Base class for warnings generated by user code. |
DeprecationWarning | Base class for warnings about deprecated features. |
PendingDeprecationWarning | Base class for warnings about features which will be deprecated in the future. |
SyntaxWarning | Base class for warnings about dubious syntax. |
RuntimeWarning | Base class for warnings about dubious runtime behavior. |
FutureWarning | Base class for warnings about constructs that will change semantically in the future. |
ImportWarning | Base class for warnings about probable mistakes in module imports. |
UnicodeWarning | Base class for warnings related to Unicode. |
BytesWarning | Base class for warnings related to bytes and bytearray . |
ResourceWarning | Base class for warnings related to resource usage. |
List of numeric operations available in Python, with an example of each.
In Python, all numeric types (except complex) support the following operations. These are sorted by ascending priority. Also note that all numeric operations have a higher priority than comparison operations.
Operation | Result | Example |
---|---|---|
x + y | Sum of x and y | RESULT 700 |
x - y | Difference of x and y | RESULT 300 |
x * y | Product of x and y | RESULT 100000 |
x / y | Quotient of x and y | RESULT 2.5 |
x // y | Floored quotient of x and y | RESULT 2 |
x % y | Remainder of x / y | RESULT 100 |
-x | x negated | RESULT -300 |
+x | x unchanged | RESULT 700 |
abs(x) | Absolute value or magnitude of x | RESULT 500 |
int(x) | x converted to integer | RESULT 500 |
float(x) | x converted to float | RESULT 500.0 |
complex(re, im) | A complex number with real part re, imaginary part im. im defaults to zero. | RESULT (490+0j) |
c.conjugate() | Conjugate of the complex number c. | RESULT (3-4j) |
divmod(x, y) | The pair (x // y, x % y) | RESULT (4, 10) |
pow(x, y) | x to the power y | RESULT 250000 |
x ** y | x to the power y | RESULT 250000 |
Further Operations for Integers & Floats
Floats and integers also include the following operations.
Operation | Result | Example |
---|---|---|
math.trunc(x) | x truncated to Integral | RESULT 123 |
round(x[, n]) | x rounded to n digits, rounding half to even. If n is omitted, it defaults to 0 . | RESULT 123 |
math.floor(x) | The greatest Integral <= x. | RESULT 123 |
math.ceil(x) | The greatest Integral >= x. | RESULT 124 |
The above are some of the most commonly used operations. The Python documentation contains a full list of math
modules that can be used on floats and integers, and cmath
modules that can be used on complex numbers.
Bitwise Operations on Integer Types
The following bitwise operations can be performed on integers. These are sorted in ascending priority.
Operation | Result | Example |
---|---|---|
x | y | Bitwise or of x and y | RESULT 508 |
x ^ y | Bitwise exclusive of x and y | RESULT 316 |
x & y | Bitwise exclusive of x and y | RESULT 192 |
x << n | x shifted left by n bits | RESULT 2000 |
x >> n | x shifted right by n bits | RESULT 125 |
~x | The bits of x inverted | RESULT -501 |
List of list methods and functions available in Python 3.
List Methods
Method | Description | Examples |
---|---|---|
append(x) | Adds an item (x) to the end of the list. This is equivalent to | RESULT ['bee', 'moth'] ['bee', 'moth', 'ant'] |
extend(iterable) | Extends the list by appending all the items from the iterable. This allows you to join two lists together. This method is equivalent to | RESULT ['bee', 'moth'] ['bee', 'moth', 'ant', 'fly'] |
insert(i, x) | Inserts an item at a given position. The first argument is the index of the element before which to insert. For example, | RESULT ['bee', 'moth'] ['ant', 'bee', 'moth'] ['ant', 'bee', 'fly', 'moth'] |
remove(x) | Removes the first item from the list that has a value of x. Returns an error if there is no such item. | RESULT ['bee', 'moth', 'ant'] ['bee', 'ant'] |
pop([i]) | Removes the item at the given position in the list, and returns it. If no index is specified, | RESULT ['bee', 'moth', 'ant'] ['bee', 'moth'] ['bee', 'moth', 'ant'] ['bee', 'ant'] |
clear() | Removes all items from the list. Equivalent to del | RESULT ['bee', 'moth', 'ant'] [] |
index(x[, start[, end]]) | Returns the position of the first list item that has a value of The optional arguments | RESULT 1 3 |
count(x) | Returns the number of times x appears in the list. | RESULT 1 2 0 |
sort(key=None, reverse=False) | Sorts the items of the list in place. The arguments can be used to customize the operation.
| RESULT [1, 2, 3, 4, 5, 6] [6, 5, 4, 3, 2, 1] ['ant', 'bee', 'moth', 'wasp'] ['bee', 'wasp', 'butterfly'] ['butterfly', 'wasp', 'bee'] |
reverse() | Reverses the elements of the list in place. | RESULT [1, 4, 2, 5, 6, 3] ['ant', 'moth', 'wasp', 'bee'] |
copy() | Returns a shallow copy of the list. Equivalent to | RESULT ['bee', 'wasp', 'moth', 'ant'] ['bee', 'wasp', 'moth', 'ant'] ['bee', 'wasp', 'moth'] ['bee', 'wasp', 'moth', 'ant'] |
List Functions
The following Python functions can be used on lists.
Method | Description | Examples |
---|---|---|
len(s) | Returns the number of items in the list. | RESULT 3 |
list([iterable]) | The | RESULT [] [] ['bee', 'moth', 'ant'] [['bee', 'moth'], ['ant']] ['b', 'e', 'e'] ['I', 'am', 'a', 'tuple'] ['am', 'I', 'a', 'set'] |
or
| Returns the largest item in an iterable (eg, list) or the largest of two or more arguments. The key argument specifies a one-argument ordering function like that used for The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a If more than one item shares the maximum value, only the first one encountered is returned. | RESULT moth wasp [1, 2, 3, 4, 5] |
or
| Returns the smallest item in an iterable (eg, list) or the smallest of two or more arguments. The key argument specifies a one-argument ordering function like that used for The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a If more than one item shares the minimum value, only the first one encountered is returned. | RESULT bee ant [1, 2, 3, 4] |
or
| Represents an immutable sequence of numbers and is commonly used for looping a specific number of times in It can be used along with | RESULT [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [51, 52, 53, 54, 55] [1, 3, 5, 7, 9] |
List of string methods available in Python 3.
Method | Description | Examples | ||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
capitalize() | Returns a copy of the string with its first character capitalized and the rest lowercased. | RESULT Bee sting | ||||||||||||||||||||||||
casefold() | Returns a casefolded copy of the string. Casefolded strings may be used for caseless matching. | RESULT bee | ||||||||||||||||||||||||
center(width[, fillchar]) | Returns the string centered in a string of length width. Padding can be done using the specified fillchar (the default padding uses an ASCII space). The original string is returned if width is less than or equal to len(s) | RESULT ----bee----- | ||||||||||||||||||||||||
count(sub[, start[, end]]) | Returns the number of non-overlapping occurrences of substring (sub) in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. Non-overlapping occurrences means that Python won't double up on characters that have already been counted. For example, using a substring of | RESULT 0 5 2 1 0 2 3 | ||||||||||||||||||||||||
encode(encoding="utf-8", errors="strict") | Returns an encoded version of the string as a bytes object. The default encoding is
| RESULT Banana b'QmFuYW5h' | ||||||||||||||||||||||||
endswith(suffix[, start[, end]]) | Returns | RESULT True True False True | ||||||||||||||||||||||||
expandtabs(tabsize=8) | Returns a copy of the string where all tab characters are replaced by one or more spaces, depending on the current column and the given tab size. Tab positions occur every tabsize characters (the default is | RESULT 1 2 3 1 2 3 1 2 3 1 2 3 | ||||||||||||||||||||||||
find(sub[, start[, end]]) | Returns the lowest index in the string where substring sub is found within the slice | RESULT 0 -1 3 3 4 -1 -1 | ||||||||||||||||||||||||
format(*args, **kwargs) | Performs a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces | RESULT Tea and Coffee Coffee and Tea Peas and Beans 1, 2, 3 Lunch: Pizza, Wine | ||||||||||||||||||||||||
format_map(mapping) | Similar to | RESULT Lunch: Pizza, Wine Lunch: Pizza, Drink Lunch: Food, Wine | ||||||||||||||||||||||||
index(sub[, start[, end]]) | Like | RESULT 0 3 3 4 ValueError: substring not found | ||||||||||||||||||||||||
isalnum() | Returns A character c is deemed to be alphanumeric if one of the following returns
| RESULT True True False False False | ||||||||||||||||||||||||
isalpha() | Returns | RESULT True False False | ||||||||||||||||||||||||
isdecimal() | Returns | RESULT True False False False False False | ||||||||||||||||||||||||
isdigit() | Returns The | RESULT True True False False False False | ||||||||||||||||||||||||
isidentifier() | Returns true if the string is a valid identifier according to the language definition, section Identifiers and keywords from the Python docs. | RESULT False True False True True | ||||||||||||||||||||||||
islower() | Returns | RESULT False False True False False True True | ||||||||||||||||||||||||
isnumeric() | Returns | RESULT True True False False False False | ||||||||||||||||||||||||
isprintable() | Returns Nonprintable characters are those characters defined in the Unicode character database as "Other" or "Separator", except for the ASCII space ( | RESULT True True True True False False False | ||||||||||||||||||||||||
isspace() | Returns Whitespace characters are those characters defined in the Unicode character database as "Other" or "Separator" and those with bidirectional property being one of "WS", "B", or "S". | RESULT False True False True True False | ||||||||||||||||||||||||
istitle() | Returns Whitespace characters are those characters defined in the Unicode character database as "Other" or "Separator" and those with bidirectional property being one of "WS", "B", or "S". | RESULT False False False True True False True True | ||||||||||||||||||||||||
isupper() | Returns | RESULT False False True False True False False | ||||||||||||||||||||||||
join(iterable) | Returns a string which is the concatenation of the strings in iterable. A | RESULT 1-2-3 U.S.A Dr. Who | ||||||||||||||||||||||||
ljust(width[, fillchar]) | Returns the string left justified in a string of length width. Padding can be done using the specified fillchar (the default padding uses an ASCII space). The original string is returned if width is less than or equal to len(s) | RESULT bee--------- | ||||||||||||||||||||||||
lower() | Returns a copy of the string with all the cased characters converted to lowercase. | RESULT bee | ||||||||||||||||||||||||
lstrip([chars]) | Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or set to | RESULT Bee ! Bee----- | ||||||||||||||||||||||||
maketrans(x[, y[, z]]) | This is a static method that returns a translation table usable for
| RESULT 123425 6782 | ||||||||||||||||||||||||
partition(sep) | Splits the string at the first occurrence of sep, and returns a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, it returns a 3-tuple containing the string itself, followed by two empty strings. | RESULT ('Python', '-', 'program') ('Python-program', '', '') | ||||||||||||||||||||||||
replace(old, new[, count]) | Returns a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is provided, only the first count occurrences are replaced. For example, if count is | RESULT Coffee bag. Coffee cup. Coffee leaves. Coffee bag. Coffee cup. Tea leaves. | ||||||||||||||||||||||||
rfind(sub[, start[, end]]) | Returns the highest index in the string where substring sub is found, such that sub is contained within | RESULT 0 8 10 9 -1 -1 -1 | ||||||||||||||||||||||||
rindex(sub[, start[, end]]) | Like | RESULT 0 8 10 9 ValueError: substring not found ValueError: substring not found ValueError: substring not found | ||||||||||||||||||||||||
rjust(width[, fillchar]) | Returns the string right justified in a string of length width. Padding can be done using the specified fillchar (the default padding uses an ASCII space). The original string is returned if width is less than or equal to len(s) | RESULT ---------bee | ||||||||||||||||||||||||
rpartition(sep) | Splits the string at the last occurrence of sep, and returns a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, it returns a 3-tuple containing the string itself, followed by two empty strings. | RESULT ('Homer-Jay', '-', 'Simpson') ('', '', 'Homer-Jay-Simpson') | ||||||||||||||||||||||||
rsplit(sep=None, maxsplit=-1) | Returns a list of the words in the string, using sep as the delimiter string. If Except for splitting from the right, | RESULT ['Homer', 'Jay', 'Simpson'] ['Homer-Jay', 'Simpson'] | ||||||||||||||||||||||||
rstrip([chars]) | Return a copy of the string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or set to | RESULT Bee ! -----Bee | ||||||||||||||||||||||||
split(sep=None, maxsplit=-1) | Returns a list of the words in the string, using sep as the delimiter string. If If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, The sep argument may consist of multiple characters (for example, If sep is not specified or is set to | RESULT ['Homer', 'Jay', 'Simpson'] ['Homer', 'Jay-Simpson'] ['Homer', '', 'Bart', ''] ['Homer', ',Bart'] ['Homer', 'Bart', 'Marge'] | ||||||||||||||||||||||||
splitlines([keepends]) | Returns a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and its value is This method splits on the following line boundaries.
| RESULT ['Tea', '', 'and coffee', 'cups'] ['Tea\n', '\n', 'and coffee\r', 'cups\r\n'] | ||||||||||||||||||||||||
startswith(prefix[, start[, end]]) | Returns | RESULT True False True False True | ||||||||||||||||||||||||
strip([chars]) | Returns a copy of the string with leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or set to | RESULT Bee ! Bee | ||||||||||||||||||||||||
swapcase() | Returns a copy of the string with uppercase characters converted to lowercase and vice versa. | RESULT hOMER sIMPSON | ||||||||||||||||||||||||
title() | Returns a title-cased version of the string. Title case is where words start with an uppercase character and the remaining characters are lowercase. | RESULT Tea And Coffee Tea And Coffee | ||||||||||||||||||||||||
translate(table) | Returns a copy of the string in which each character has been mapped through the given translation table. The table must be an object that implements indexing via | RESULT 123425 6782 | ||||||||||||||||||||||||
upper() | Returns a copy of the string with all the cased characters converted to uppercase. | RESULT BEE | ||||||||||||||||||||||||
zfill(width) | Returns a copy of the string left filled with ASCII | RESULT 00036 -0036 +0036 |
Heirarchical structure of the built-in exceptions in Python 3.
BaseException
List of operators available in Python 3.
Arithmetic Operators
Operator | Name | Operation | Result | Example |
---|---|---|---|---|
+ | Addition | x + y | Sum of x and y | RESULT 700 |
- | Subtraction | x - y | Difference of x and y | RESULT 300 |
* | Multiplication | x * y | Product of x and y | RESULT 100000 |
/ | Division | x / y | Quotient of x and y | RESULT 2.5 |
// | Floor Division | x // y | Floored quotient of x and y | RESULT 2 |
% | Modulus | x % y | Remainder of x / y | RESULT 100 |
** | Exponent | x ** y | x to the power y | RESULT 250000 |
Unary Operations for +
and -
A unary operation is an operation with one operand.
Operator | Meaning | Operation | Result | Example |
---|---|---|---|---|
+ | Unary positive | +x | x unchanged | RESULT 700 |
- | Unary negative | -x | x negated | RESULT -300 |
Comparison (Relational) Operators
Comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation.
Operator | Meaning | Operation | Result | Example |
---|---|---|---|---|
== | Equal to | x == y | True if x is exactly equal to y . Otherwise False . | RESULT True False |
!= | Not equal to | x != y | True if x is not equal to y . Otherwise False . | RESULT False True |
> | Greater than | x > y | True if x is greater than y . Otherwise False . | RESULT False True |
< | Less than | x < y | True if x is less than y . Otherwise False . | RESULT True False |
>= | Greater than or equal to | x >= y | True if x is greater than or equal to y . Otherwise False . | RESULT True False |
<= | Less than or equal to | x <= y | True if x is less than or equal to y . Otherwise False . | RESULT True False |
Logical Operators
Operator | Operation | Result | Example |
---|---|---|---|
and | x and y | True if both x and y are True . Otherwise False . | RESULT True False |
or | x or y | True if either x or y are True . Otherwise False . | RESULT True False |
not | not x == y or not(x == y) | If x is True then return False . | RESULT False True False |
Assignment Operators
Operator | Operation | Result | Example |
---|---|---|---|
= | z = x + y | Assigns the value of its right operand/s to its left operand. | RESULT 3 |
+= | x += y | Same as x = x + y . | RESULT 3 |
-= | x -= y | Same as x = x - y . | RESULT -1 |
*= | x *= y | Same as x = x * y . | RESULT 6 |
/= | x /= y | Same as x = x / y . | RESULT 3.0 |
%= | x %= y | Same as x = x % y . | RESULT 2 |
**= | x **= y | Same as x = x ** y . | RESULT 16 |
//= | x //= y | Same as x = x // y . | RESULT 6 |
Bitwise Operators
The following bitwise operations can be performed on integers. These are sorted in ascending priority.
Operator | Operation | Result | Example |
---|---|---|---|
| | x | y | Bitwise or of x and y | RESULT 508 |
^ | x ^ y | Bitwise exclusive of x and y | RESULT 316 |
& | x & y | Bitwise exclusive of x and y | RESULT 192 |
<< | x << n | x shifted left by n bits | RESULT 2000 |
>> | x >> n | x shifted right by n bits | RESULT 125 |
~ | ~x | The bits of x inverted | RESULT -501 |
The @
Operator
Python also lists the @
symbol as an operator. The @
symbol is used for the Python decorator syntax. A decorator is any callable Python object that is used to modify a function, method or class definition. A decorator is passed the original object being defined and returns a modified object, which is then bound to the name in the definition.
If you're interested in learning more about Python decorators, see the Python wiki.
Ternary (Conditional) Operator
In Python, you can define a conditional expression like this:
The condition (C
) is evaluated first. If it returns True
, the result is x
, otherwise it's y
.
Example:
Low
List of string operators available in Python 3.
Operator | Description | Operation | Example | |||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
+ | Concatenates (joins) string1 and string2 | string1 + string2 | RESULT Tea Leaf | |||||||||||||||||||||||||||
* | Repeats the string for as many times as specified by x | string * x | RESULT Bee Bee Bee | |||||||||||||||||||||||||||
[] | Slice — Returns the character from the index provided at x. | string[x] | RESULT e | |||||||||||||||||||||||||||
[:] | Range Slice — Returns the characters from the range provided at x:y. | string[x:y] | RESULT room | |||||||||||||||||||||||||||
in | Membership — Returns True if x exists in the string. Can be multiple characters. | x in string | RESULT True False True | |||||||||||||||||||||||||||
not in | Membership — Returns True if x does not exist in the string. Can be multiple characters. | x not in string | RESULT False True False | |||||||||||||||||||||||||||
r | Suppresses an escape sequence (\x ) so that it is actually rendered. In other words, it prevents the escape character from being an escape character. | r"\x" | RESULT 1 Bee 2\tTea | |||||||||||||||||||||||||||
% | Performs string formatting. It can be used as a placeholder for another value to be inserted into the string. The
| %x |
List of escape sequences available in Python 3.
Escape Sequence | Description | Example |
---|---|---|
\newline | Backslash and newline ignored | RESULT line1 line2 line3 |
\\ | Backslash (\ ) | RESULT \ |
\' | Single quote (' ) | RESULT ' |
\" | Double quote (" ) | RESULT " |
\a | ASCII Bell (BEL) | |
\b | ASCII Backspace (BS) | RESULT Hello World! |
\f | ASCII Formfeed (FF) | RESULT Hello World! |
\n | ASCII Linefeed (LF) | RESULT Hello World! |
\r | ASCII Carriage Return (CR) | RESULT Hello World! |
\t | ASCII Horizontal Tab (TAB) | RESULT Hello World! |
\v | ASCII Vertical Tab (VT) | RESULT Hello World! |
\ooo | Character with octal value ooo | RESULT Hello World! |
\xhh | Character with hex value hh | RESULT Hello World! |
Comments
Post a Comment