All Go Rust Python PHP JavaScript
Chrome Dev Summit to secure your spot in workshops, office hours and learning lounges!

How to Reverse a String in Python

In Python, there are 3 ways to reverse a string. Using slicing Slice notation takes the form [start:stop:step]. #!/usr/bin/python3 s = "Hello World" print(s[::-1]) # syntax # a[start:stop] # items start through stop-1 # a[start:] # items...
pooriabt

How to Prettyprint a JSON File in Python

In Python, there are 2 ways to prettyprint a JSON file. Using json module The json module already implements some basic pretty printing in the dump and dumps functions, with the indent parameter that specifies how many spaces to indent by: #!/us...
Patcher56

How to Check If an Object Is of a Given Type in Python

In Python, there are 2 ways to check if an object is of a given type. Using isinstance Method The isinstance(object, classinfo) method returns True if the object argument is an instance of the classinfo argument, or of a (direct, indirect, or virtua...
Unused

How to Read from Stdin in Python

In Python, there are 3 ways to read from stdin. Using fileinput Module This module implements a helper class and functions to quickly write a loop over standard input or a list of files. For example, #!/usr/bin/python3 # Import module import f...
pooriabt

How to Extract Extension from Filename in Python

In Python, there are 2 ways to extract extension from filename. Using os.path.splitext Method The os.path.splitext(path) method splits the pathname path into a pair (root, ext) such that root + ext == path, and the extension, ext, is empty or begins...
Unused

How to Generate Random Integers Between 0 and 9 in Python

In Python, there are 3 ways to generate random integers between 0 and 9. Using randrange Method The random.randrange(start, stop[, step]) method returns a randomly selected element from range(start, stop, step). For example, #!/usr/bin/python3 ...
Patcher56

How to Get the Class Name of an Instance in Python

In Python, there are 3 ways to get the class name of an instance. Using type Method The type(object) method returns the type of an object. For example, #!/usr/bin/python3 class A: pass a = A() name = type(a).__name__ print(name) A ...
Sambhav Khandelwal

How to Pad a Numeric String with Zeros to the Left in Python

In Python, there are 3 ways to pad a numeric string with zeros to the left. Using zfill Method The str.zfill(width) method returns a copy of the string left filled with ASCII '0' digits to make a string of length width. For example, #!/usr/bin/...
Patcher56

How to Delete an Item from a Dictionary in Python

In Python, there are 2 ways to delete an item from a dictionary. Using del Statement The easiest way to delete an item from a dictionary in Python: #!/usr/bin/python3 m = {"a":1, "b":2} # remove a if 'a' in m: del m['a'] print(m) {'b': 2...
Patcher56

How to Remove a Trailing Newline in Python

In Python, there are 4 ways to remove a trailing newline. Using rstrip Method The str.rstrip() method returns a copy of the string with trailing characters removed. For example, #!/usr/bin/python3 s = "\nab c\r\n" # str.rstrip([chars]) n = s....
Tomoki

How to Count the Occurrences of a List Item in Python

In Python, there are 3 ways to count the occurrences of a list item. Using count Method The str.count() method returns the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpr...
Patcher56

How to Randomly Select a Element from List in Python

In Python, there are 3 ways to randomly select a element from list. Using random.choice Method The random.choice() method returns a random element from the non-empty sequence seq. If seq is empty, raises IndexError. For example, #!/usr/bin/pyth...
Tomoki

How to Know If an Object has an Attribute in Python

In Python, there are 4 ways to know if an object has an attribute. Using hasattr Method The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. For example, #!/usr/...
ada

How to Remove an Element From a List by Index in Python

In Python, there are 3 ways to remove an element from a list by index. Using del Keyword There is a way to remove an item from a list given its index instead of its value. For example, #!/usr/bin/python3 # -*- coding: utf8 -*- l = [1, 2, 3, 4]...
Unused

How to Limit Floats to Two Decimal Points in Python

In Python, there are 4 ways to limit floats to two decimal points. Using format Method You can use str.format() function to limit floats, it really simple. For example, #!/usr/bin/python3 # -*- coding: utf8 -*- f = 13.949999999999999 print("{:...
Unused