.lower()
, .upper()
,.capitalize()
"funKY tOwn".capitalize()
"funky tOwn".lower()
"fUNKY tOWN".swapcase()
How you call this:
.split([sep [,maxsplit]])
"funKY tOwn".split()
"funKY tOwn".capitalize().split()
[x.capitalize() for x in "funKY tOwn".split()]
"I want to take you to, funKY tOwn".split("u")
"I want to take you to, funKY tOwn".split("you")
.strip()
, .join()
, .replace()
¶csv_string = 'Dog,Cat,Spam,Defenestrate,1, 3.1415 \n\t'
csv_string.strip()
clean_list = [x.strip() for x in csv_string.split(",")]
print(clean_list)
.join()
allows you to glue a list of strings together with a certain string
print(",".join(clean_list))
print("\t".join(clean_list))
.replace()
strings in strings
csv_string = 'Dog,Cat,Spam,Defenestrate,1, 3.1415 \n\t'
alt_csv = csv_string.strip().replace(' ','')
print(alt_csv)
print(csv_string.strip().replace(' ','').replace(',','\t'))
.find()
¶incredibly useful searching, returning the index of the search
s = 'My Funny Valentine'
s.find("y")
s.find("y",2)
s[s.find("Funny"):]
s.find("z")
ss = [s,"Argentine","American","Quarentine"]
for thestring in ss:
if thestring.find("tine") != -1:
print("'" + str(thestring) + "' contains 'tine'.")
string
module¶exposes useful variables and functions
import string
string.ascii_letters
string.digits
casting using str() is very limited Python gives access to C-like string formatting
usage: “%(format)” % (variable)
import math
print("My favorite integer is %i and my favorite float is %f,\n"
" which to three decimal places is %.3f and in exponential form is %e"
% (3,math.pi,math.pi,math.pi))
common formats:
f (float), i (integer), s (string), g (nicely formatting floats)
http://docs.python.org/release/2.7.2/library/stdtypes.html#string-formatting-operations
% escapes “%”
print("I promise to give 100%% effort whenever asked of %s." % ("me"))
+ and zero-padding
print("%f\n%+f\n%f\n%010f\n%10s" % (math.pi,math.pi,-1.0*math.pi,math.pi,"pi"))
'on {0}, I feel {1}'.format("saturday","groovy")
'on {}, I feel {}'.format("saturday","groovy")
'on {0}, I feel {1}'.format(["saturday","groovy"])
'on {0}, I feel {0}'.format(["saturday","groovy"])
'on {0}, I feel {0}'.format("saturday","groovy")
you can assign by argument position or by name
'{desire} to {place}'.format(desire='Fly me',\
place='The Moon')
'{desire} to {place} or else I wont visit {place}.'.format( \
desire='Fly me',place='The Moon')
f = {"desire": "I want to take you", "place": "funky town"}
'{desire} to {place}'.format(**f)
("%03.2f" % 3.14159) == "{:03.2f}".format(3.14159)
"{0:03.2f}".format(3.14159,42)
"{1:03.2f}".format(3.14159,42)
# format also supports binary numbers
"int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
.open()
and .close()
are builtin functions
%%file mydata.dat
This is my zeroth file I/O. Zing!
file_stream = open('mydata.dat','r') ; print(type(file_stream))
file_stream.close()
open modes: r
(read), w
(write), r+
(read + update), rb
(read as a binary stream, ...), rt
(read as text file)
Writing data: .write()
or .writelines()
f= open("test.dat","w")
f.write("This is my first file I/O. Zing!")
f.close()
!cat test.dat
f= open("test.dat","w")
f.writelines(["a=['This is my second file I/O.']\n","Take that Dr. Zing!\n"])
f.close()
!cat test.dat
Likewise, there is .readlines()
and .read()
f= open("test.dat","r")
data = f.readlines()
f.close() ; print(data)
%%file tabbify_my_csv.py
"""
small copy program that turns a csv file into a tabbed file
PYTHON BOOT CAMP EXAMPLE;
created by Josh Bloom at UC Berkeley, 2010,2012,2013,2015 (ucbpythonclass+bootcamp@gmail.com)
"""
import os
def tabbify(infilename,outfilename,ignore_comments=True,comment_chars="#;/"):
"""
INPUT: infilename
OUTPUT: creates a file called outfilename
"""
if not os.path.exists(infilename):
return # do nothing if the file isn't there
f = open(infilename,"r")
o = open(outfilename,"w")
inlines = f.readlines() ; f.close()
outlines = []
for l in inlines:
if ignore_comments and (l[0] in comment_chars):
outlines.append(l)
else:
outlines.append(l.replace(",","\t"))
o.writelines(outlines) ; o.close()
%run tabbify_my_csv.py
tabbify("google_share_price.csv","google_share_price.tsv")
!cat google_share_price.csv |head
!cat google_share_price.tsv |head
shutil
module is preferred for copying, archiving & removing files/directories
http://docs.python.org/library/shutil.html#module-shutil
tempfile
module is used for the creation of temporary directories and files
import tempfile
tmp = tempfile.TemporaryFile() ; type(tmp)
tmp = tempfile.NamedTemporaryFile(suffix=".csv",\
prefix="boot",dir="/tmp",delete=False)
print(tmp.name)
tmp.write(bytes("# stock phrases of today's youth\nWassup?!,OMG,LOL,BRB,Python\n","utf-8"))
tmp.close()
!cat $tmp.name
tmp = tempfile.NamedTemporaryFile(suffix=".csv",\
prefix="boot",dir="/tmp",delete=False)
print(tmp.name)
tmp.write(b"# stock phrases of today's youth\nWassup?!,OMG,LOL,BRB,Python\n")
tmp.close()
!cat $tmp.name
io
module StringIO
/BytesIO
¶handy for making file-like objects out of strings
import io
myfile = io.StringIO( \
"# stock phrases of today's youth\nWassup?!,OMG,LOL,BRB,Python\n")
myfile.getvalue() ## get what we just wrote
myfile.seek(0) ## go back to the beginning
myfile.readlines()
myfile.close()
myfile.write('not gonna happen')
myfile = io.BytesIO(b"# stock phrases of today's youth\nWassup?!,OMG,LOL,BRB,Python\n")
myfile.seek(2) ; myfile.write(b"silly wah wah") ; myfile.seek(0)
myfile.readlines()
subprocess
module¶subprocess
is the preferred way to interact with other programs, as you might do on the command line
from subprocess import *
p = Popen("ls", shell=True, stdout=PIPE) # list the directory
p.pid # get the process ID of the new subprocess
print(p.stdout.readlines())
p = Popen("vanRossum-Trump-2016", shell=True, stdout=PIPE,stderr=PIPE)
print(p.stderr.readlines())
it's often advisable to wait until the subprocess has finished
p = Popen("find .. -name '*.py'", shell=True, stdout=PIPE,stderr=PIPE)
os.waitpid(p.pid, 0) ## this will block until the search is done
(c) J Bloom 2013-2015 All Rights Reserved