DOC PREVIEW
USF CS 110 - Strings

This preview shows page 1 out of 2 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 2 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 2 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

1StringsStrings• A string is a series of characters• Characters can be referenced by usingbrackets• The first character is at position 0mystring = “the”letter = mystring[2] #letter becomes ‘e’tmystringh e0 1 2length• The len function returns the length of a stringmystring=“bob”len(mystring) #3len(“adam”) #4length=len(mystring)last = mystring[len-1] #retrieves last charfor loopsmystring = "CS is cool!"for c in mystring: print cindex=0while index < len(mystring):print mystring[index]index += 1Exercises1. Write a for or while loop to print a stringbackwardsSlices• Select a segment of a string• Specify [start:end]– include start but do not include end– if you do not specify start slice starts from thebeginning– if you do not specify end slices goes to endmystring=“CS is cool”print mystring[6:10]print mystring[2:7]print mystring[:4]print mystring[:]2String Comparison/in• == tests to see if strings are the same• >, < compares strings alphabetically• The in operator tests whether a given characterappears in a given string– ‘c’ in “chocolate” #true– ‘z’ in “chocolate” #falseImmutability• Strings are immutable– they cannot be changedstring module• Contains useful methods for stringshttp://docs.python.org/lib/string-methods.html• Dot notation allows us to call a method ona string objectimport stringmystring=“adam”string.find(mystring, “a”) #returns index of first instance foundmystring=“CS is cool”mystring.split() #result [‘CS’,’is’,’cool’]newstring = mystring.replace(“CS”, “Econ”)Exercises1. Write a program that prompts the userfor two strings and determines thenumber of two-character sequences thatappear in both the first and secondstrings. Exclude spaces in yourcomparison.• “CS is cool” “the old cow” would have twomatches “co” for “cool” and “cow” and “ol”for “cool” and


View Full Document

USF CS 110 - Strings

Download Strings
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Strings and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Strings 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?