Python Foundation Flashcards
Return - string
Args - none
___________
returns a string with first letter capitalized and all other characters lowercased. It doesn’t modify the original string
string.capitalize()
Return - int
Args - (substring, start, end)
___________
searches the substring in the given string and returns how many times the substring is present in it. It also takes optional parameters start and end to specify the starting and ending positions in the string respectively.
string.count()
Return - True/False
Args - (suffix, start, end)
___________
returns True if a string ends with the specified suffix. If not, it returns False.
string.endswith()
Return - byte string
Args - (encoding=’UTF-8’,errors=’strict’)
___________
By default, encode() method doesn’t require any parameters.
It returns utf-8 encoded version of the string. In case of failure, it raises a UnicodeDecodeError exception.
However, it takes two parameters:
1) encoding - the encoding type a string has to be encoded to
2) errors - response when encoding fails.
There are six types of error response:
strict - default response which raises a UnicodeDecodeError exception on failure
ignore - ignores the unencodable unicode from the result
replace - replaces the unencodable unicode to a question mark ?
xmlcharrefreplace - inserts XML character reference instead of unencodable unicode
backslashreplace - inserts a \uNNNN espace sequence instead of unencodable unicode
namereplace - inserts a \N{…} escape sequence instead of unencodable unicode
string.encode()
Return - index
Args - (substring, start, end)
___________
returns the index of first occurrence of the substring (if found). If not found, it returns -1. Start and End args are optional.
string.find()
Return - formatted string with inputs
Args - (first input, second input, …)
___________
reads the type of arguments passed to it and formats it according to the format codes defined in the string. First value in given string is the argument it references and will substitute for in the given parameters, first number after colon is the number of total spaces allocated to the entire inputted argument, number after decimal with the f is the number of decimal places after the input number
“blah blah {0} blah blah {1:5.3f}”.format(‘input0’, ‘input2’)
Return - index
Args - (substring, start, end)
___________
returns the index of a substring inside the string (if found). If the substring is not found, it raises an exception
string.index()
Return - True/False
Args - none
___________
returns True if all characters in a string are digits. If not, it returns False
string.isdigit()
Return - concatenated string
Args - (iterable)
___________
provides a flexible way to concatenate string. It concatenates each element of an iterable (such as list, string and tuple) to the string and returns the concatenated string
separator = ‘, ‘
separator.join(someIterable)
Return - string
Args - (width, ‘optional fill char’)
___________
returns a left or right-justified string of a given minimum width.
string.ljust() and rjust()
Return - lowercased version of string
Args - none
___________
converts all uppercase characters in a string into lowercase characters and returns it.
string.lower()
Return - stripped string
Args - (‘char’) or ([char1, char2, …])
___________
removes characters from the leading left or right based on the argument (a string specifying the set of characters to be removed).
string.lstrip() and rstrip()
Return - stripped string
Args - (‘char’) or ([char1, char2, …])
___________
removes characters from both left and right based on the argument (a string specifying the set of characters to be removed).
The strip() returns a copy of the string with both leading and trailing characters stripped.
When the combination of characters in the chars argument mismatches the character of the string in the left, it stops removing the leading characters.
Similarly, when the combination of characters in the chars argument mismatches the character of the string in the right, it stops removing the trailing characters.
string.strip()
Return - 3-tuple
Args - (separator)
___________
splits the string at the first occurrence of the argument string and returns a tuple containing the part the before separator, argument string and the part after the separator.
The partition method returns a 3-tuple containing:
the part before the separator, separator parameter, and the part after the separator if the separator parameter is found in the string
string itself and two empty strings if the separator parameter is not found
string.partition()
Return - string
Args - (old substring, new substring, number of times you want it replaced with)
___________
returns a copy of the string where all occurrences of a substring is replaced with another substring.
string.replace()
Return - index
Args - (substring, start, end)
___________
returns the highest index of the substring (if found). If not found, it returns -1.
The rfind() method takes maximum of three parameters:
sub - It’s the substring to be searched in the str string.
start and end (optional) - substring is searched within str[start:end]
string.rfind()
Return - list of strings
Args - (separator, max # of splits desired)
___________
breaks up a string at the specified separator and returns a list of strings.
The split() method takes maximum of 2 parameters:
separator (optional)- The is a delimiter. The string splits at the specified separator.
If the separator is not specified, any whitespace (space, newline etc.) string is a separator.
maxsplit (optional) - The maxsplit defines the maximum number of splits.
The default value of maxsplit is -1, meaning, no limit on the number of splits.
string.split()
Return - list of strings
Args - (separator, max # of splits desired)
___________
splits string from the right at the specified separator and returns a list of strings.
The rsplit() method takes maximum of 2 parameters:
separator (optional)- The is a delimiter. The rsplit() method splits string starting from the right at the specified separator.
If the separator is not specified, any whitespace (space, newline etc.) string is a separator.
maxsplit (optional) - The maxsplit defines the maximum number of splits.
The default value of maxsplit is -1, meaning, no limit on the number of splits.
string.rsplit()
Return - boolean
Args - ( iterable )
___________
returns True if any element of an iterable is True. If not, any() returns False. If empty, returns returns False.
string.any()
Return - tuples of (counter, iterable)
Args - ( iterable, optional start value )
___________
adds counter to an iterable and returns it (the enumerate object).
The enumerate() method takes two parameters:
iterable - a sequence, an iterator, or objects that supports iteration
start (optional) - enumerate() starts counting from this number. If start is omitted, 0 is taken as start.
enumerate( iterable, start=0 )
Return - an iteratOR
Args - ( function, iterable )
___________
constructs an iterator from elements of an iterable for which a function returns true.
filters the given iterable with the help of a function that tests each element in the iterable to be true or not.
filter()
The filter() function in Python is a built-in function that allows you to process an iterable and extract those items that satisfy a given condition
Return - map object
Args - ( function, iterable )
___________
applies a given function to each item of an iterable (list, tuple etc.) and returns a map of the results.
this map can then be wrapped by the list() method to create a list of the results, or wrapped by a set() method, etc
map()
Return - slice object
Args - ( optional start, stop, optional step )
___________
creates a slice object representing the set of indices specified by range(start, stop, step).
The slice object is used to slice a given sequence (string, bytes, tuple, list or range) or any object which supports sequence protocol (implements __getitem__() and __len__() method).
slice()
Return - sorted list
Args - ( iterable, optional reverse=True, optional function that serves as a key to the sort comparison )
___________
returns a sorted list from the given iterable.
sorted()
Return - iterator of tuples
Args - ( 1st iterable, 2nd iterable, etc)
___________
take iterables (can be zero or more), makes iterator that aggregates elements based on the iterables passed, and returns an iterator of tuples.
zip()
Return - none
Args - ( some list to add to end )
___________
extends the list by adding all items of a list (passed as an argument) to the end.
list1.extend(list2)
Return - none
Args - ( index, value to insert )
___________
inserts an element to the list at a given index.
list.insert(index, element)
Return - none
Args - ( value to insert )
___________
searches for the given element in the list and removes the first matching element.
list.remove(element)
Return - none
Args - ( value to find )
___________
finds the given element in a list and returns its position.
However, if the same element is present more than once, index() method returns its smallest/first position.
If not found, it raises a ValueError exception indicating the element is not in the list.
list.index(element)
Return - none
Args - ( value to count )
___________
counts how many times an element has occurred in a list and returns it.
list.count(element)
Return - none
Args - ( optional index to remove from the list )
___________
takes a single argument (index) and removes the item present at that index.
If the index passed to the pop() method is not in range, it throws IndexError: pop index out of range exception.
The parameter passed to the pop() method is optional. If no parameter is passed, the default index -1 is passed as an argument which returns the last item.
list.pop(index)
Return - none
Args - none
___________
reverses the elements of a given list.
list.reverse()
Return - none
Args - ( optional function that acts as key for the sort comparison, reverse = True/False )
___________
sorts the elements of a given list in a specific order - Ascending or Descending.
list.sort( key= … , reverse= … )
Return - the new sorted list
Args - ( list, optional function that acts as key for the sort comparison, reverse = True/False )
___________
sorts the elements of a given list in a specific order - Ascending or Descending.
sorted( list, key= … , reverse= … )
Return - returns an entirely new list (not a reference!)
Args - none
___________
if you need the original list unchanged when the new list is modified, you can use copy() method. This is called shallow copy.
new_list = list.copy()
~ same as ~
new_list = list[ : ]
~ same as ~
new_list = list( old_list )
Return - none
Args - none
___________
removes all items from the list.
list.clear()
Return - boolean
Args - ( iterable )
___________
returns:
True if at least one element of an iterable is true
False if all elements are false or if an iterable is empty
any(iterable)
Return - boolean
Args - ( iterable )
___________
returns:
True - If all elements in an iterable are true
False - If any element in an iterable is false
all( iterable )
Return - string
Args - ( object like a string, list, etc )
___________
returns a string containing printable representation of an object.
ascii( object )
Return - a new iterable that passes the function
Args - ( function, iterable )
___________
filters the given iterable with the help of a function that tests each element in the iterable to be true or not.
filter( function, iterable )
Return - iterator
Args - ( sets / tuples to turn into iterator, optional value that is the end of the sequence )
___________
creates an object which can be iterated one element at a time.
These objects are useful when coupled with loops like for loop, while loop.
iter( object, sentinel )
Return - list
Args - ( opttional set / tuple / list / dict / etc )
___________
constructor creates a list in Python.
The list() constructor returns a mutable sequence list of elements.
If no parameters are passed, it creates an empty list
If iterable is passed as parameter, it creates a list of elements in the iterable
new_list = list( some optional iterable )
~ same as ~
new_list = [ ]
~ same as ~
new_list = list.copy( old list )
Return - list of mapped results
Args - ( mapping function, iterable to be mapped )
___________
applies a given function to each item of an iterable (list, tuple etc.) and returns a list of the results.
map( function, iterable, … )
Return - reversed list
Args - ( some sequence )
___________
returns the reversed iterator of the given sequence.
*if you don’t want anything returned, just do list.reverse()
reversed( sequence )
sort() vs sorted() difference
sort() method sorts the list in-place, mutating the list indices, and returns None (like all in-place operations)
The sorted() function returns a new sorted list, leaving the original list unaffected
reverse() vs reversed() difference
reverse() method reverses the list in-place, mutating the list indices, and returns None (like all in-place operations)
The reversed() function returns a new reversed list, leaving the original list unaffected
a = [1,2,3,4,5,6,7,8]
a[1:4]
a = [1,2,3,4,5,6,7,8]
a[1:4]
returns [2,3,4]
indexes at 0 and does NOT include the last index
a = [1,2,3,4,5,6,7,8]
a[1:4:2]
a = [1,2,3,4,5,6,7,8]
a[1:4:2]
returns [2, 4]
slices along increments of 2 starting at your first index listed
a = [1,2,3,4,5,6,7,8]
a[ : : -1]
a = [1,2,3,4,5,6,7,8]
a[ : : -1]
returns [8, 7, 6, 5, 4, 3, 2, 1]
slices the list in reverse
a = [1, 2, 3, 4, 5]
sliceObj = slice(1, 3)
a[sliceObj]
a = [1, 2, 3, 4, 5]
sliceObj = slice(1, 3)
a[sliceObj]
return [2, 3]