Skip to content

Instantly share code, notes, and snippets.

@roshanlabh
Created January 25, 2022 14:08
Show Gist options
  • Save roshanlabh/d8b596d7dd0e64fdebf6309fe936996b to your computer and use it in GitHub Desktop.
Save roshanlabh/d8b596d7dd0e64fdebf6309fe936996b to your computer and use it in GitHub Desktop.
Python cheat sheet

Python self help guide

Datatypes and their conversion functions are:

  • integer: int()
  • float: float()
  • string: str()
  • boolean: bool()
  • list: list()

To print, use

print('Hello world')
print("Hello, world!")

To know datatype, use type function

type(variable)

To get a help of any function, use

help(str)
?str

You cannot concate (+) the string with integer and vice versa. Only same datatype can be used with + operator.

  • If it is used with string then it will be concatenation of two strings.
  • If it is used with integer then it will be addition of two numbers
  • If it is used with list then it will be merge two lists in one.

Common string functions:

name = "Roshan Labh"

To convert in upper case

name.upper()

To get the string len

len(name)

To get the count of number of occurance of a string. Below, will give how many times o is there name variable

name.count('o')

To find a string in string. If it's not found then it will return -1

name.find('o')

List operations list is defined as:

names = ['Roshan', 'Ram', 'Mohan']

To add in the list

names.appened('John')

To edit in the list

names[0] = 'Roshan Labh'

To delete from the list. Will delete Mohan from the list

del(names[2])
numbers = [5, 2, 1, 5, 7, 4]
numbers.append(20)
numbers.insert(10)
numbers.remove(5) // remove by value
numbers.pop()
numbers.count(5)  // will retun number of occurance of 5 in the list
numbers.index(5)
numbers.index(50)   // will through error if not found
5 in numbers  // return Boolean on found
numbers2 = numbers.copy()  // create a copy of the list
numbers.sort()    // sort in ascending order
numbers.reverse() // sort in descending order

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment