Examples Using Strings and Lists
Quick glance at some of the things you can do with functions working with strings and lists.
Size 2.7 kB - File type text/python-sourceFile contents
#
#Comp 171 Standard Python Script Header
#Assignment name: Simple Read and Write of Files
#LUC id and Name: whonig@luc.edu Dr. William L. Honig
#Date 12 Feb 12
#
#The basics of Python string and lists
#
#Questions: In Python these are examples of sequences - things in an order
# What else would you like to do with a sequence?
#
#
def simpleStrings():
aString = "This is a string of words."
bString = 'This is the same string of words (almost).'
cString = "A string with a quote in it right here ' inside the string"
dString = 'It works this way for a quote " as well'
print( aString, bString, cString, dString, sep="\n" )
#string can be indexed - selecting parts of them
#the index starts with zero for the "first" item
eString = aString[0]
#what happens if you go past the end of the string?
print( eString, aString[0:4], aString[10:13], len(aString), aString[ len(aString)-1 ], "done")
def simpleLists():
#lists use square brackets and commas between each item in the list
aList = [ "This", "is", "a", "list", "of", "strings", "." ]
bList = [ 1, 2, 67, -45, 12, 13, 1, 67 ]
cList = [ "a list can contain", 34, "many things", 2 ]
dList = [ aList, bList, 67, "a string" ]
print( aList, bList, cList, dList, sep="\n" )
#lists are indexed same as strings
print( aList[0], aList[1], aList[2], aList[len(aList)-1])
def workFunctions():
#there are many helper functions to work with lists and strings
aString = "This is a string of words."
aList = [ "This", "is", "a", "list", "of", "strings", "." ]
bList = [ 1, 2, 67, -45, 12, 13, 1, 67 ]
#our old friends + and * work with them just fine
print( aString*2, aList + bList, sep="\n", end="\n" )
print()
#check these out
aList.reverse()
print( aList, end="\n" )
print()
print( min(bList), max(bList), len(bList), sep="\n", end="\n" )
print()
print( aString.index("words"), aList.count("is"), bList.count(1), sep="\n" )
print()
aList.reverse()
aList.append( " " )
aList.extend("And ")
aList.append("more!")
print( aList )
print()
#what's the difference between extend and append? Can you tell?
bList.sort()
print( bList )
print()
bString = aString.replace("string", "list")
cList = bString.split()
print( cList )
print()
cString = aString.center(40)
print( cString )
print()
def tryPrint():
print( "a", "b", "c")
print()
print( "a", "b", "c", sep="\n")
print( "a", "b", "c", end="\n")
print( "a", "b", "c", sep="\n", end="\n")
print( "What is going on with the end parameter?", end="Nothing" )
Click here to get the file