Skip to main content

All about PYTHON 3


List of built-in exceptions in Python 3.

Base Classes

These exceptions are generally used as base classes for other exceptions.

ExceptionDescription
BaseExceptionThe base class for all built-in exceptions. It is not meant to be directly inherited by user-defined classes (for that, use Exception below).
ExceptionAll built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from this class.
ArithmeticErrorThe base class for built-in exceptions that are raised for various arithmetic errors. These are: OverflowErrorZeroDivisionErrorFloatingPointError.
BufferErrorRaised when a buffer related operation cannot be performed.
LookupErrorThe 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.

ExceptionDescription
AssertionErrorRaised when an assert statement fails.
AttributeError

Raised when an attribute reference or assignment fails.

EOFErrorRaised when the input() function hits an end-of-file condition (EOF) without reading any data.
FloatingPointErrorRaised when a floating point operation fails.
GeneratorExitRaised when a generator or coroutine is closed. Technically, this is not an error, and the GeneratorExit exception directly inherits from BaseException instead of Exception.
ImportErrorRaised 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.
ModuleNotFoundErrorA 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.
IndexErrorRaised when a sequence subscript is out of range.
KeyErrorRaised when a mapping (dictionary) key is not found in the set of existing keys.
KeyboardInterruptRaised when the user hits the interrupt key (typically Control-C or Delete).
MemoryErrorRaised when an operation runs out of memory but the situation may still be rescued (by deleting some objects).
NameErrorRaised when a local or global name is not found. This applies only to unqualified names.
NotImplementedErrorThis 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".
OverflowErrorRaised when the result of an arithmetic operation is too large to be represented.
RecursionErrorThis exception is derived from RuntimeError. It is raised when the interpreter detects that the maximum recursion depth is exceeded.
ReferenceErrorRaised 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.
RuntimeErrorRaised when an error is detected that doesn̢۪t fall in any of the other categories.
StopIterationRaised by the next() function and an iterator's __next__() method to signal that there are no further items produced by the iterator.
StopAsyncIterationMust be raised by __anext__() method of an asynchronous iterator object to stop the iteration.
SyntaxErrorRaised when the parser encounters a syntax error.
IndentationErrorBase class for syntax errors related to incorrect indentation. This is a subclass of SyntaxError.
TabErrorRaised when indentation contains an inconsistent use of tabs and spaces. This is a subclass of IndentationError.
SystemErrorRaised when the interpreter finds an internal error, but it's not serious enough to exit the interpreter.
SystemExitThis exception is raised by the sys.exit() function, and (when it is not handled) causes the Python interpreter to exit.
TypeErrorRaised when an operation or function is applied to an object of inappropriate type.
UnboundLocalErrorRaised 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.
UnicodeErrorRaised when a Unicode-related encoding or decoding error occurs. It is a subclass of ValueError.
UnicodeEncodeErrorRaised when a Unicode-related error occurs during encoding. It is a subclass of UnicodeError.
UnicodeDecodeErrorRaised when a Unicode-related error occurs during encoding. It is a subclass of UnicodeError.
UnicodeTranslateErrorRaised when a Unicode-related error occurs during encoding. It is a subclass of UnicodeError.
ValueErrorRaised 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.
ZeroDivisionErrorRaised 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.

ExceptionDescription
BlockingIOErrorRaised when an operation would block on an object (e.g. socket) set for non-blocking operation.
ChildProcessErrorRaised when an operation on a child process failed.
ConnectionErrorA base class for connection-related issues.
BrokenPipeErrorA 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.
ConnectionAbortedErrorA subclass of ConnectionError, raised when a connection attempt is aborted by the peer.
ConnectionRefusedErrorA subclass of ConnectionError, raised when a connection is reset by the peer.
FileExistsErrorRaised when trying to create a file or directory which already exists.
FileNotFoundErrorRaised when a file or directory is requested but doesn̢۪t exist.
InterruptedErrorRaised when a system call is interrupted by an incoming signal.
IsADirectoryErrorRaised when a file operation is requested on a directory.
NotADirectoryErrorRaised when a directory operation is requested on something which is not a directory.
PermissionErrorRaised when trying to run an operation without the adequate access rights.
ProcessLookupErrorRaised when a given process doesn̢۪t exist.
TimeoutErrorRaised when a system function timed out at the system level.

Warnings

The following exceptions are used as warning categories.

ExceptionDescription
WarningBase class for warning categories.
UserWarningBase class for warnings generated by user code.
DeprecationWarningBase class for warnings about deprecated features.
PendingDeprecationWarningBase class for warnings about features which will be deprecated in the future.
SyntaxWarningBase class for warnings about dubious syntax.
RuntimeWarningBase class for warnings about dubious runtime behavior.
FutureWarningBase class for warnings about constructs that will change semantically in the future.
ImportWarningBase class for warnings about probable mistakes in module imports.
UnicodeWarningBase class for warnings related to Unicode.
BytesWarningBase class for warnings related to bytes and bytearray.
ResourceWarningBase 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.

OperationResultExample
x + ySum of x and y
print(500 + 200)
RESULT
700
x - yDifference of x and y
print(500 - 200)
RESULT
300
x * yProduct of x and y
print(500 * 200)
RESULT
100000
x / yQuotient of x and y
print(500 / 200)
RESULT
2.5
x // yFloored quotient of x and y
print(500 // 200)
RESULT
2
x % yRemainder of x / y
print(500 % 200)
RESULT
100
-xx negated
print(-500 + 200)
RESULT
-300
+xx unchanged
print(+500 + 200)
RESULT
700
abs(x)Absolute value or magnitude of x
print(abs(-500))
RESULT
500
int(x)x converted to integer
print(int(500.26))
RESULT
500
float(x)x converted to float
print(float(500))
RESULT
500.0
complex(re, im)A complex number with real part re, imaginary part imim defaults to zero.
print(complex(500, 10j))
RESULT
(490+0j)
c.conjugate()Conjugate of the complex number c.
c = 3+4j
print(c.conjugate())
RESULT
(3-4j)
divmod(x, y)The pair (x // y, x % y)
print(divmod(94, 21))
RESULT
(4, 10)
pow(x, y)x to the power y
print(pow(500, 2))
RESULT
250000
x ** yx to the power y
print(500 ** 2)
RESULT
250000

Further Operations for Integers & Floats

Floats and integers also include the following operations.

OperationResultExample
math.trunc(x)x truncated to Integral
import math
x = 123.56
print(math.trunc(x))
RESULT
123
round(x[, n])x rounded to n digits, rounding half to even. If n is omitted, it defaults to 0.
x = 123.56
print(round(x, 1))
RESULT
123
math.floor(x)The greatest Integral <= x.
import math
x = 123.56
print(math.floor(x))
RESULT
123
math.ceil(x)The greatest Integral >= x.
import math
x = 123.56
print(math.ceil(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.

OperationResultExample
x | yBitwise or of x and y
print(500 | 200)
RESULT
508
x ^ yBitwise exclusive of x and y
print(500 ^ 200)
RESULT
316
x & yBitwise exclusive of x and y
print(500 & 200)
RESULT
192
x << nx shifted left by n bits
print(500 << 2)
RESULT
2000
x >> nx shifted right by n bits
print(500 >> 2)
RESULT
125
~xThe bits of x inverted
print(~500)
RESULT
-501

 

List of list methods and functions available in Python 3.

List Methods

MethodDescriptionExamples
append(x)

Adds an item (x) to the end of the list. This is equivalent to a[len(a):] = [x].

a = ["bee", "moth"]
print(a)
a.append("ant")
print(a)
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 a[len(a):] = iterable.

a = ["bee", "moth"]
print(a)
a.extend(["ant", "fly"])
print(a)
RESULT
['bee', 'moth']
['bee', 'moth', 'ant', 'fly']
insert(ix)

Inserts an item at a given position. The first argument is the index of the element before which to insert. For example, a.insert(0, x) inserts at the front of the list.

a = ["bee", "moth"]
print(a)
a.insert(0, "ant")
print(a)
a.insert(2, "fly")
print(a)
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.

a = ["bee", "moth", "ant"]
print(a)
a.remove("moth")
print(a)
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, pop() removes and returns the last item in the list.

# Example 1: No index specified
a = ["bee", "moth", "ant"]
print(a)
a.pop()
print(a)
# Example 2: Index specified
a = ["bee", "moth", "ant"]
print(a)
a.pop(1)
print(a)
RESULT
['bee', 'moth', 'ant']
['bee', 'moth']
['bee', 'moth', 'ant']
['bee', 'ant']
clear()

Removes all items from the list. Equivalent to del a[:].

a = ["bee", "moth", "ant"]
print(a)
a.clear()
print(a)
RESULT
['bee', 'moth', 'ant']
[]
index(x[, start[, end]])

Returns the position of the first list item that has a value of x. Raises a ValueError if there is no such item.

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

a = ["bee", "ant", "moth", "ant"]
print(a.index("ant"))
print(a.index("ant", 2))
RESULT
1
3
count(x)

Returns the number of times x appears in the list.

a = ["bee", "ant", "moth", "ant"]
print(a.count("bee"))
print(a.count("ant"))
print(a.count(""))
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.

key
Specifies a function of one argument that is used to extract a comparison key from each list element. The default value is None (compares the elements directly).
reverse
Boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.
a = [3,6,5,2,4,1]
a.sort()
print(a)
a = [3,6,5,2,4,1]
a.sort(reverse=True)
print(a)
a = ["bee", "wasp", "moth", "ant"]
a.sort()
print(a)
a = ["bee", "wasp", "butterfly"]
a.sort(key=len)
print(a)
a = ["bee", "wasp", "butterfly"]
a.sort(key=len, reverse=True)
print(a)
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.

a = [3,6,5,2,4,1]
a.reverse()
print(a)
a = ["bee", "wasp", "moth", "ant"]
a.reverse()
print(a)
RESULT
[1, 4, 2, 5, 6, 3]
['ant', 'moth', 'wasp', 'bee']
copy()

Returns a shallow copy of the list. Equivalent to a[:].

# WITHOUT copy()
a = ["bee", "wasp", "moth"]
b = a
b.append("ant")
print(a)
print(b)
# WITH copy()
a = ["bee", "wasp", "moth"]
b = a.copy()
b.append("ant")
print(a)
print(b)
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.

MethodDescriptionExamples
len(s)

Returns the number of items in the list.

a = ["bee", "moth", "ant"]
print(len(a))
RESULT
3
list([iterable])

The list() constructor returns a mutable sequence list of elements. The iterable argument is optional. You can provide any sequence or collection (such as a string, list, tuple, set, dictionary, etc). If no argument is supplied, an empty list is returned.

print(list())
print(list([]))
print(list(["bee", "moth", "ant"]))
print(list([["bee", "moth"], ["ant"]]))
a = "bee"
print(list(a))
a = ("I", "am", "a", "tuple")
print(list(a))
a = {"I", "am", "a", "set"}
print(list(a))
RESULT
[]
[]
['bee', 'moth', 'ant']
[['bee', 'moth'], ['ant']]
['b', 'e', 'e']
['I', 'am', 'a', 'tuple']
['am', 'I', 'a', 'set']

max(iterable, *[, keydefault])

or

max(arg1arg2, *args[, key])

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 sort().

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 ValueError is raised.

If more than one item shares the maximum value, only the first one encountered is returned.

a = ["bee", "moth", "ant"]
print(max(a))
a = ["bee", "moth", "wasp"]
print(max(a))
a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 4]
print(max(a, b))
RESULT
moth
wasp
[1, 2, 3, 4, 5]

min(iterable, *[, keydefault])

or

min(arg1arg2, *args[, key])

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 sort().

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 ValueError is raised.

If more than one item shares the minimum value, only the first one encountered is returned.

a = ["bee", "moth", "wasp"]
print(min(a))
a = ["bee", "moth", "ant"]
print(min(a))
a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 4]
print(min(a, b))
RESULT
bee
ant
[1, 2, 3, 4]

range(stop)

or

range(startstop[, step])

Represents an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops.

It can be used along with list() to return a list of items between a given range.

print(list(range(10)))
print(list(range(1,11)))
print(list(range(51,56)))
print(list(range(1,11,2)))
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.

MethodDescriptionExamples
capitalize()

Returns a copy of the string with its first character capitalized and the rest lowercased.

a = "bee sting" 
print(a.capitalize())
RESULT
Bee sting
casefold()Returns a casefolded copy of the string. Casefolded strings may be used for caseless matching.
a = "BEE"
print(a.casefold())
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)
a = "bee" 
b = a.center(12, "-")
print(b)
RESULT
----bee-----
count(sub[, start[, end]])

Returns the number of non-overlapping occurrences of substring (sub) in the range [startend]. 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 xxx against xxxx returns 1.

a = "Mushroooom soup" 
print(a.count("O"))
print(a.count("o"))
print(a.count("oo"))
print(a.count("ooo"))
print(a.count("Homer"))
print(a.count("o", 4, 7))
print(a.count("o", 7))
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 utf-8errors may be given to set a different error handling scheme. The possible value for errors are:

  • strict (encoding errors raise a UnicodeError)
  • ignore
  • replace
  • xmlcharrefreplace
  • backslashreplace
  • any other name registered via codecs.register_error()
from base64 import b64encode
a = "Banana"
print(a)
a = b64encode(a.encode())
print(a)
RESULT
Banana
b'QmFuYW5h'
endswith(suffix[, start[, end]])

Returns True if the string ends with the specified suffix, otherwise it returns Falsesuffix can also be a tuple of suffixes. When the (optional) start argument is provided, the test begins at that position. With optional end, the test stops comparing at that position.

a = "Banana"
print(a.endswith("a"))
print(a.endswith("nana"))
print(a.endswith("z"))
print(a.endswith("an", 1, 3))
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 8, giving tab positions at columns 0, 8, 16 and so on).

a = "1\t2\t3"
print(a)
print(a.expandtabs())
print(a.expandtabs(tabsize=12))
print(a.expandtabs(tabsize=2))
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 s[start:end]. Optional arguments start and end are interpreted as in slice notation. Returns -1 if sub is not found.

a = "Fitness"
print(a.find("F"))
print(a.find("f"))
print(a.find("n"))
print(a.find("ness"))
print(a.find("ess"))
print(a.find("z"))
print(a.find("Homer"))
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 {}. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.

# Example 1
print("{} and {}".format("Tea", "Coffee"))
# Example 2
print("{1} and {0}".format("Tea", "Coffee"))
# Example 3
print("{lunch} and {dinner}".format(lunch="Peas", dinner="Beans"))
# Example 4
print("{0}, {1}, {2}".format(*"123"))
# Example 5
lunch = {"food": "Pizza", "drink": "Wine"}
print("Lunch: {food}, {drink}".format(**lunch))
RESULT
Tea and Coffee
Coffee and Tea
Peas and Beans
1, 2, 3
Lunch: Pizza, Wine
format_map(mapping)

Similar to format(**mapping), except that mapping is used directly and not copied to a dictionary. This is useful if for example mapping is a dict subclass.

# Example 1
lunch = {"Food": "Pizza", "Drink": "Wine"}
print("Lunch: {Food}, {Drink}".format_map(lunch))
# Example 2
class Default(dict):
    def __missing__(self, key):
      return key
lunch = {"Food": "Pizza"}
print("Lunch: {Food}, {Drink}".format_map(Default(lunch)))
lunch = {"Drink": "Wine"}
print("Lunch: {Food}, {Drink}".format_map(Default(lunch)))
RESULT
Lunch: Pizza, Wine
Lunch: Pizza, Drink
Lunch: Food, Wine
index(sub[, start[, end]])

Like find() (above), but raises a ValueError when the substring is not found (find() returns -1 when the substring isn't found).

a = "Fitness"
print(a.index("F"))
print(a.index("n"))
print(a.index("ness"))
print(a.index("ess"))
print(a.index("z"))   #Error
RESULT
0
3
3
4
ValueError: substring not found
isalnum()

Returns True if all characters in the string are alphanumeric and there is at least one character. Returns False otherwise.

A character c is deemed to be alphanumeric if one of the following returns True:

  • c.isalpha()
  • c.isdecimal()
  • c.isdigit()
  • c.isnumeric()
c = "Fitness"
print(c.isalnum())
c = "123"
print(c.isalnum())
c = "1.23"
print(c.isalnum())
c = "$*%!!!"
print(c.isalnum())
c = "0.34j"
print(c.isalnum())
RESULT
True
True
False
False
False
isalpha()

Returns True if all characters in the string are alphabetic and there is at least one character. Returns False otherwise.

c = "Fitness"
print(c.isalpha())
c = "123"
print(c.isalpha())
c = "$*%!!!"
print(c.isalpha())
RESULT
True
False
False
isdecimal()

Returns True if all characters in the string are decimal characters and there is at least one character. Returns False otherwise.

c = "123"
print(c.isdecimal())
c = u"\u00B2"
print(c.isdecimal())
c = "1.23"
print(c.isdecimal())
c = "u123"
print(c.isdecimal())
c = "Fitness"
print(c.isdecimal())
c = "$*%!!!"
print(c.isdecimal())
RESULT
True
False
False
False
False
False
isdigit()

Returns True if all characters in the string are digits and there is at least one character. Returns False otherwise.

The isdigit() method is often used when working with various unicode characters, such as for superscripts (eg, 2).

c = "123"
print(c.isdigit())
c = u"\u00B2"
print(c.isdigit())
c = "1.23"
print(c.isdigit())
c = "u123"
print(c.isdigit())
c = "Fitness"
print(c.isdigit())
c = "$*%!!!"
print(c.isdigit())
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.

a = "123"
print(a.isidentifier())
a = "_user_123"
print(a.isidentifier())
a = "_user-123"
print(a.isidentifier())
a = "Homer"
print(a.isidentifier())
a = "for"
print(a.isidentifier())
RESULT
False
True
False
True
True
islower()

Returns True if all cased characters in the string are lowercase and there is at least one cased character. Returns False otherwise.

a = " "
print(a.islower())
a = "123"
print(a.islower())
a = "_user_123"
print(a.islower())
a = "Homer"
print(a.islower())
a = "HOMER"
print(a.islower())
a = "homer"
print(a.islower())
a = "HOMER"
a = a.casefold() #Force lowercase
print(a.islower())
RESULT
False
False
True
False
False
True
True
isnumeric()

Returns True if all characters in the string are numeric characters, and there is at least one character. Returns False otherwise.

c = "123"
print(c.isnumeric())
c = u"\u00B2"
print(c.isnumeric())
c = "1.23"
print(c.isnumeric())
c = "u123"
print(c.isnumeric())
c = "Fitness"
print(c.isnumeric())
c = "$*%!!!"
print(c.isnumeric())
RESULT
True
True
False
False
False
False
isprintable()

Returns True if all characters in the string are printable or the string is empty. Returns False otherwise.

Nonprintable characters are those characters defined in the Unicode character database as "Other" or "Separator", except for the ASCII space (0x20) which is considered printable.

a = ""
print(a.isprintable())
a = " "
print(a.isprintable())
a = u"\u00B2"
print(a.isprintable())
a = "Bart"
print(a.isprintable())
a = "\t"
print(a.isprintable())
a = "\r\n"
print(a.isprintable())
a = "Bart \r"
print(a.isprintable())
RESULT
True
True
True
True
False
False
False
isspace()

Returns True if there are only whitespace characters in the string and there is at least one character. Returns False otherwise.

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".

a = ""
print(a.isspace())
a = " "
print(a.isspace())
a = "Bart"
print(a.isspace())
a = "\t"
print(a.isspace())
a = "\r\n"
print(a.isspace())
a = "Bart \r"
print(a.isspace())
RESULT
False
True
False
True
True
False
istitle()

Returns True if the string is a titlecased string and there is at least one character (for example uppercase characters may only follow uncased characters and lowercase characters only cased ones). Returns False otherwise.

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".

a = ""
print(a.istitle())
a = " "
print(a.istitle())
a = " t"
print(a.istitle())
a = " T"
print(a.istitle())
a = "Tea"
print(a.istitle())
a = "Tea and Coffee"
print(a.istitle())
a = "Tea And Coffee"
print(a.istitle())
a = "1. Tea & Coffee \r"
print(a.istitle())
RESULT
False
False
False
True
True
False
True
True
isupper()

Returns True if all cased characters in the string are uppercase and there is at least one cased character. Returns False otherwise.

a = " "
print(a.isupper())
a = "123"
print(a.isupper())
a = "_USER_123"
print(a.isupper())
a = "Homer"
print(a.isupper())
a = "HOMER"
print(a.isupper())
a = "homer"
print(a.isupper())
a = "HOMER"
a = a.casefold() #Force lowercase
print(a.isupper())
RESULT
False
False
True
False
True
False
False
join(iterable)

Returns a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.

a = "-"
print(a.join("123"))
a = "."
print(a.join("USA"))
a = ". "
print(a.join(("Dr", "Who")))
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)
a = "bee" 
b = a.ljust(12, "-")
print(b)
RESULT
bee---------
lower()

Returns a copy of the string with all the cased characters converted to lowercase.

a = "BEE"
print(a.lower())
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 None, the chars argument defaults to removing whitespace.

a = "      Bee      "
print(a.lstrip(), "!")
a = "-----Bee-----"
print(a.lstrip("-"))
RESULT
Bee       !
Bee-----
maketrans(x[, y[, z]])

This is a static method that returns a translation table usable for str.translate().

  • If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or set to None. Character keys will then be converted to ordinals.
  • If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y.
  • If there is a third argument, it must be a string, whose characters will be mapped to None in the result.
frm = "SecrtCod"
to = "12345678"
trans_table = str.maketrans(frm, to)
secret_code = "Secret Code".translate(trans_table)
print(secret_code)
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.

a = "Python-program"
print(a.partition("-"))
print(a.partition("."))
RESULT
('Python', '-', 'program')
('Python-program', '', '')
replace(oldnew[, 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 3, only the first 3 occurrences are replaced.

a = "Tea bag. Tea cup. Tea leaves."
print(a.replace("Tea", "Coffee"))
print(a.replace("Tea", "Coffee", 2))
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 s[start:end]. Optional arguments start and end are interpreted as in slice notation. This method returns -1 on failure.

a = "Yes Fitness"
print(a.rfind("Y"))
print(a.rfind("e"))
print(a.rfind("s"))
print(a.rfind("ss"))
print(a.rfind("y"))
print(a.rfind("z"))
print(a.rfind("Homer"))
RESULT
0
8
10
9
-1
-1
-1
rindex(sub[, start[, end]])

Like rfind() but raises ValueError when the substring sub is not found.

a = "Yes Fitness"
print(a.rindex("Y"))
print(a.rindex("e"))
print(a.rindex("s"))
print(a.rindex("ss"))
print(a.rindex("y"))
print(a.rindex("z"))
print(a.rindex("Homer"))
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)
a = "bee" 
b = a.rjust(12, "-")
print(b)
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.

a = "Homer-Jay-Simpson"
print(a.rpartition("-"))
print(a.rpartition("."))
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 maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or is set to None, any whitespace string is a separator.

Except for splitting from the right, rsplit() behaves like split() which is described below.

a = "Homer Jay Simpson"
print(a.rsplit())
a = "Homer-Jay-Simpson"
print(a.rsplit(sep="-",maxsplit=1))
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 None, the chars argument defaults to removing whitespace.

a = "      Bee      "
print(a.rstrip(), "!")
a = "-----Bee-----"
print(a.rstrip("-"))
RESULT
Bee !
-----Bee
split(sep=None, maxsplit=-1)

Returns a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If maxsplit is not specified or -1, then there is no limit on the number of splits.

If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']).

The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']). Splitting an empty string with a specified separator returns [''].

If sep is not specified or is set to None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

a = "Homer Jay Simpson"
print(a.split())
a = "Homer-Jay-Simpson"
print(a.split(sep="-",maxsplit=1))
a = "Homer,,Bart,"
print(a.split(","))
a = "Homer,,Bart"
print(a.split(",", maxsplit=1))
a = "Homer<>Bart<>Marge"
print(a.split("<>"))
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 True.

This method splits on the following line boundaries.

RepresentationDescription
\nLine Feed
\rCarriage Return
\n\rCarriage Return + Line Feed
\v or \x0bLine Tabulation
\f or \x0cForm feed
\x1cFile separator
\x1dGroup separator
\x1eRecord separator
\x85Next Line (C1 Control Code)
\u2028Line separator
\u2029Paragraph separator
a = "Tea\n\nand coffee\rcups\r\n"
print(a.splitlines())
print(a.splitlines(keepends=True))
RESULT
['Tea', '', 'and coffee', 'cups']
['Tea\n', '\n', 'and coffee\r', 'cups\r\n']
startswith(prefix[, start[, end]])

Returns True if the string starts with the specified prefix, otherwise it returns Falseprefix can also be a tuple of prefixes. When the (optional) start argument is provided, the test begins at that position. With optional end, the test stops comparing at that position.

a = "Homer"
print(a.startswith("H"))
print(a.startswith("h"))
print(a.startswith("Homer"))
print(a.startswith("z"))
print(a.startswith("om", 1, 3))
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 None, the chars argument defaults to removing whitespace.

a = "      Bee      "
print(a.strip(), "!")
a = "-----Bee-----"
print(a.strip("-"))
RESULT
Bee !
Bee
swapcase()

Returns a copy of the string with uppercase characters converted to lowercase and vice versa.

a = "Homer Simpson"
print(a.swapcase())
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.

a = "tea and coffee"
print(a.title())
a = "TEA AND COFFEE"
print(a.title())
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 __getitem__(), typically a mapping or sequence.

frm = "SecrtCod"
to = "12345678"
trans_table = str.maketrans(frm, to)
secret_code = "Secret Code".translate(trans_table)
print(secret_code)
RESULT
123425 6782
upper()

Returns a copy of the string with all the cased characters converted to uppercase.

a = "bee"
print(a.upper())
RESULT
BEE
zfill(width)

Returns a copy of the string left filled with ASCII 0 digits to make a string of length width. A leading sign prefix (+/-) is handled by inserting the padding after the sign character rather than before. The original string is returned if width is less than or equal to len(s).

a = "36"
print(a.zfill(5))
a = "-36"
print(a.zfill(5))
a = "+36"
print(a.zfill(5))
RESULT
00036
-0036
+0036

Heirarchical structure of the built-in exceptions in Python 3.

List of operators available in Python 3.

Arithmetic Operators

OperatorNameOperationResultExample
+Additionx + ySum of x and y
print(500 + 200)
RESULT
700
-Subtractionx - yDifference of x and y
print(500 - 200)
RESULT
300
*Multiplicationx * yProduct of x and y
print(500 * 200)
RESULT
100000
/Divisionx / yQuotient of x and y
print(500 / 200)
RESULT
2.5
//Floor Divisionx // yFloored quotient of x and y
print(500 // 200)
RESULT
2
%Modulusx % yRemainder of x / y
print(500 % 200)
RESULT
100
**Exponentx ** yx to the power y
print(500 ** 2)
RESULT
250000

Unary Operations for + and -

unary operation is an operation with one operand.

OperatorMeaningOperationResultExample
+Unary positive+xx unchanged
print(+500 + 200)
RESULT
700
-Unary negative-xx negated
print(-500 + 200)
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.

OperatorMeaningOperationResultExample
==Equal tox == yTrue if x is exactly equal to y. Otherwise False.
print(1==1)
print(1==2)
RESULT
True
False
!=Not equal tox != yTrue if x is not equal to y. Otherwise False.
print(1!=1)
print(1!=2)
RESULT
False
True
>Greater thanx > yTrue if x is greater than y. Otherwise False.
print(1>2)
print(2>1)
RESULT
False
True
<Less thanx < yTrue if x is less than y. Otherwise False.
print(1<2)
print(2<1)
RESULT
True
False
>=Greater than or equal tox >= yTrue if x is greater than or equal to y. Otherwise False.
print(1>=1)
print(1>=2)
RESULT
True
False
<=Less than or equal tox <= yTrue if x is less than or equal to y. Otherwise False.
print(1<=1)
print(2<=1)
RESULT
True
False

Logical Operators

OperatorOperationResultExample
andx and yTrue if both x and y are True. Otherwise False.
print(1==1 and 2==2)
print(1==1 and 1==2)
RESULT
True
False
orx or yTrue if either x or y are True. Otherwise False.
print(1==1 or 1==2)
print(1==2 or 3==4)
RESULT
True
False
notnot x == y or not(x == y)If x is True then return False.
print(not True)
print(not False)
print(not(1==1))
RESULT
False
True
False

Assignment Operators

OperatorOperationResultExample
=z = x + yAssigns the value of its right operand/s to its left operand.
a = 1 + 2
print(a)
RESULT
3
+=x += ySame as x = x + y.
a = 1
a += 2
print(a)
RESULT
3
-=x -= ySame as x = x - y.
a = 1
a -= 2
print(a)
RESULT
-1
*=x *= ySame as x = x * y.
a = 2
a *= 3
print(a)
RESULT
6
/=x /= ySame as x = x / y.
a = 6
a /= 2
print(a)
RESULT
3.0
%=x %= ySame as x = x % y.
a = 6
a %= 4
print(a)
RESULT
2
**=x **= ySame as x = x ** y.
a = 2
a **= 4
print(a)
RESULT
16
//=x //= ySame as x = x // y.
a = 25
a //= 4
print(a)
RESULT
6

Bitwise Operators

The following bitwise operations can be performed on integers. These are sorted in ascending priority.

OperatorOperationResultExample
|x | yBitwise or of x and y
print(500 | 200)
RESULT
508
^x ^ yBitwise exclusive of x and y
print(500 ^ 200)
RESULT
316
&x & yBitwise exclusive of x and y
print(500 & 200)
RESULT
192
<<x << nx shifted left by n bits
print(500 << 2)
RESULT
2000
>>x >> nx shifted right by n bits
print(500 >> 2)
RESULT
125
~~xThe bits of x inverted
print(~500)
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:

x if C else y

The condition (C) is evaluated first. If it returns True, the result is x, otherwise it's y.

Example:

a = 7
print("Low" if a < 10 else "High")
RESULT
Low

List of string operators available in Python 3.

OperatorDescriptionOperationExample
+Concatenates (joins) string1 and string2string1 + string2
a = "Tea " + "Leaf"
print(a)
RESULT
Tea Leaf
*Repeats the string for as many times as specified by xstring * x
a = "Bee " * 3
print(a)
RESULT
Bee Bee Bee
[]Slice — Returns the character from the index provided at x.string[x]
a = "Sea"
print(a[1])
RESULT
e
[:]Range Slice — Returns the characters from the range provided at x:y.string[x:y]
a = "Mushroom"
print(a[4:8])
RESULT
room
inMembership — Returns True if x exists in the string. Can be multiple characters.x in string
a = "Mushroom"
print("m" in a)
print("b" in a)
print("shroo" in a)
RESULT
True
False
True
not inMembership — Returns True if x does not exist in the string. Can be multiple characters.x not in string
a = "Mushroom"
print("m" not in a)
print("b" not in a)
print("shroo" not in a)
RESULT
False
True
False
rSuppresses 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"
a = "1" + "\t" + "Bee"
b = "2" + r"\t" + "Tea"
print(a)
print(b)
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 % symbol is a prefix to another character (x) which defines the type of value to be inserted. The value to be inserted is listed at the end of the string after another % character.

CharacterDescription
%cCharacter.
%sString conversion via str() prior to formatting.
%iSigned decimal integer.
%dSigned decimal integer.
%uUnsigned decimal integer.
%oOctal integer.
%xHexadecimal integer using lowercase letters.
%XHexadecimal integer using uppercase letters.
%eExponential notation with lowercase e.
%EExponential notation with uppercase e.
%fFloating point real number.
%gThe shorter of %f and %e.
%GThe shorter of %f and %E.
%x

List of escape sequences available in Python 3.

Escape SequenceDescriptionExample
\newlineBackslash and newline ignored
print("line1 \
line2 \
line3")
RESULT
line1 line2 line3
\\Backslash (\)
print("\\")
RESULT
\
\'Single quote (')
print('\'')
RESULT
'
\"Double quote (")
print("\"")
RESULT
"
\aASCII Bell (BEL)
print("\a")
\bASCII Backspace (BS)
print("Hello \b World!")
RESULT
Hello  World!
\fASCII Formfeed (FF)
print("Hello \f World!")
RESULT
Hello 
 World!
\nASCII Linefeed (LF)
print("Hello \n World!")
RESULT
Hello 
 World!
\rASCII Carriage Return (CR)
print("Hello \r World!")
RESULT
Hello 
 World!
\tASCII Horizontal Tab (TAB)
print("Hello \t World!")
RESULT
Hello      World!
\vASCII Vertical Tab (VT)
print("Hello \v World!")
RESULT
Hello 
 World!
\oooCharacter with octal value ooo
print("\110\145\154\154\157\40\127\157\162\154\144\41")
RESULT
Hello World!
\xhh


Character with hex value hh
print("\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64\x21")
RESULT
Hello World!

Comments

Popular posts from this blog

Advanced Java Solved manual 5th Sem (Information Technology)

By Harsh Tambade Contributor : Vishal Chavare  Advanced Java Programming Solved Manual 22517                    Advanced Java Programming Solved Manual 22517 Download Now👇👇 Practical No. 1  Practical No. 2  Practical No. 3  Practical No. 4  Practical No. 5  Practical No. 6  Practical No. 7  Practical No. 8  Practical No. 9  Practical No.9 Practical No. 12 Practical No. 16 Practical No. 18 Practical No.18 Practical No. 19 Practical No .19 Practical No. 20 Practical No. 21 Practical No. 22 Practical No. 23 Practical No. 24   Advanced Java Programming Solved Manual 22517 here's also a full solved manual but the clarity is not too good so please refer the below links: download full manual

Advanced computer network (ACN) solved manual

By Harsh Tambade Download link:   https://rmpalwe.files.wordpress.com/2019/09/acn-practical_manual-19-20-1.pdf

Flask cheatsheet

  Flask Cheatsheet Loading... Importing Flask from flask import Flask Copy Most used import functions These are some of the most used import functions from flask import Flask , render_template , redirect , url_for , request Copy Boilerplate This is the basic template or barebone structure of Flask. from flask import Flask app = Flask ( __name__ ) @app . route ( "/" ) def hello_world ( ) : return "<p>Hello, World!</p>" app . run ( ) Copy route(endpoint) This is to make different endpoints in our flask app. @app . route ( "/" ) Copy Route method Allowing get and post requests on an endpoint. methods = [ 'GET' , 'POST' ] Copy Re-run while coding This is used to automatically rerun the program when the file is saved. app . run ( debug = True ) Copy Change host This is used to change the host. app . run ( host = '0.0.0.0' ) Copy Change port This is used to change the port. app . run ( port = 80 ) Copy SQ