yorkie = 'Marlowe' mutt = 'Kafka' ylen = len(yorkie) #length of variable yorkie print(ylen) #prints 7 print(len(yorkie)) #does the same thing len(yorkie) #also does the same thing, print is implicit print(yorkie.lower()) #lower cases the string print(yorkie.strip('aeiou')) #removes vowels from end of string print(mutt.split('f')) #splits "Kafka" into ['Ka', 'ka'] print(mutt.count('a')) #prints 2, the number of a's in string yorkie.replace('a','4') #replace a's with 4's
colorvalues = {'red' : 1, 'blue' : 2, 'green' : 3, 'yellow' : 4, 'orange' : 5} colorvalues #prints {'blue': 2, 'orange': 5, 'green': 3, 'yellow': 4, 'red': 1} colorvalues['blue'] #prints 2 colorvalues.keys() #retrieves all keys as a list: #['blue', 'orange', 'green', 'yellow', 'red'] colorvalues.pop('blue') #prints 2 and removes the blue key/value pair colorvalues #after pop, we have: #{'orange': 5, 'green': 3, 'yellow': 4, 'red': 1}
groceries = ['ham','spam','eggs'] len(groceries) #returns 3 print groceries[1] #prints spam for x in groceries: print x.upper() #prints HAM SPAM EGGS groceries[2] = 'bacon' groceries #list is now ['ham','spam','bacon'] groceries.append('eggs') groceries #list is now ['ham', 'spam', 'bacon', 'eggs'] groceries.sort() groceries #list is now ['bacon', 'eggs', 'ham', 'spam']
file read:
def printSmiles(): text = open("file.txt", "w").readlines() for line in text: print line
listing files in a directory
from os import listdir for f in listdir('.'): print('Processing {} file...'.format(f))
important libs:
cat names.txt | namecount_py
namecount_py:
#!/usr/bin/env python3 import sys def count_names(): names = {} for name in sys.stdin.readlines(): name = name.strip() if name in names: names[name] += 1 else: names[name] = 1 for name, count in names.items(): sys.stdout.write("{0}\t{1}\n".format(name, count)) if __name__ == "__main__": count_names()
#!/usr/bin/python import os from time import strftime stamp = strftime("%Y-%m-%d %H:%M:%S") logfile = '/path/to/your/logfile.log' path = '/path/to/tmp/directory/' files = os.listdir(path) bytes = 0 numfiles = 0 for f in files: if f.startswith('sess_'): info = os.stat(path + f) numfiles += 1 bytes += info[6] if numfiles > 1: title = 'files' else: title = 'file' string = stamp + " -- " + str(numfiles) + " session " \ + title +", " + str(bytes) + " bytes\n" file = open(logfile,"a") file.writelines(string) file.close()
basic program:
#! /usr/bin/env python def smile( ): print("Smile!", end="") for i in range(3,0,-1): for j in range(i): smile() print("")
pip install csvkit <code> ==== JSON ==== <code python> import json data = json.loads('{ "foo": 1, "bar": [10, "apples"] }') sample = { "blue": [1,2], "ocean": "water" } json_string = json.dumps(sample)
to transfer files across newtwork computers
python -m SimpleHTTPServer