Python Cheatsheet

Diference between print and return:

  • print prints to the screen

  • return can be captured in a variable

General Methods

  • .append - adds item to the list or the dict

  • .pop - "pops" out the last item by default or the item with the index

    • lists: my_list.pop(<item_number>)

    • dicts: dict.pop('key')

  • .upper - uppercases all letters

  • .lower - lowercases all letters

  • .capitalize - Capitalizez first letter and lowercase the rest

  • .isdigit - Checks if the string is a digit and returns a boolean value (True or False)

  • .format - This will replace {0} with the value provided in the format method

    • Example sentence = "The sum of 5 + 10 is {0}".format(50)

  • .sort - will sort the list in ascending order

    • Example my_list.sort() # Sorts the list to [1,2,3,4,5]

  • .reverse - will reverse the current order

    • Example my_list.reverse() # Reverses it to [5,4,3,2,1]

  • .index('a') - shows the index position of 'a'

  • .count('a') - counts how many times 'a' appers in the list

  • .strip - removes starting or ending spaces

Dictionary Methods

  • .keys - will print only the keys

  • .values - will print only the values

  • .get("weight") - will get the value of the key

  • .items - gets the whole entry from the dictionary

    • Example:

for entry in employees.items():
	print(entry)

String manipulation methods

  1. Some of the methods offered by strings are:

capitalize() – changes all string letters to capitals; center() – centers the string inside the field of a known length; count() – counts the occurrences of a given character; join() – joins all items of a tuple/list into one string; lower() – converts all the string's letters into lower-case letters; lstrip() – removes the white characters from the beginning of the string; replace() – replaces a given substring with another; rfind() – finds a substring starting from the end of the string; rstrip() – removes the trailing white spaces from the end of the string; split() – splits the string into a substring using a given delimiter; strip() – removes the leading and trailing white spaces; swapcase() – swaps the letters' cases (lower to upper and vice versa) title() – makes the first letter in each word upper-case; upper() – converts all the string's letter into upper-case letters.

  1. String content can be determined using the following methods (all of them return Boolean values):

endswith() – does the string end with a given substring? isalnum() – does the string consist only of letters and digits? isalpha() – does the string consist only of letters? islower() – does the string consists only of lower-case letters? isspace() – does the string consists only of white spaces? isupper() – does the string consists only of upper-case letters? startswith() – does the string begin with a given substring?

Last updated