Code

This is the future home of some of some code snippets. Not much here right now.

1. Recursively print all the items in a nested list
This recursive function will print all the items in the given list nested to any depth.

def printlist(list): if list: if type(list[0]) == type([]): printlist(list[0]) else: print list[0] printlist(list[1:])

2. Break text into groups of five
This snippet will take text and break it into groups of five characters, padding any remainder with Xs.

# Group text import re if len(text) % 5 != 0: text += "X" * (5 - (len(text) % 5)) text=" ".join(re.compile('\w{5}').findall(text))

3. Left-pad a number with zeros
This function will pad a number with an arbitrary number of zeros to the left.

# n is a string representing the number def padleft(n, places): if len(n) < places: padded = (places - (len(n) % places)) * "0" + n return padded else: return n

Leave a Reply