250 likes | 382 Vues
String Methods. CSIS 1595: Fundamentals of Programming and P roblem Solving 1. Object-oriented Programming. Strings are considered “ objects ” in Python. Object. Methods to access state of object. Current state of object. Programmer who writes code using an object.
E N D
String Methods CSIS 1595: Fundamentals of Programming and Problem Solving 1
Object-oriented Programming • Strings are considered “objects” in Python Object Methods toaccess state of object Current stateof object Programmer who writes code using an object Only has to understand how to call methods, not how they work Does not have to understand internal representation of object state
Object-Oriented Syntax variablename.methodname(arguments) • Example: capitalizing the string namename = fredcapname = name.capitalize()print(capname) Fred Like a normal function call Name of specific object the method is applied to
String Methods • Comprehensive list at http://docs.python.org/3.3/library/stdtypes.html#string-methods • General categories: • Search • Formatting • Modification (capitalizing, etc.) • Etc.
String Modification Methods • Case changing: • capitalize: Returns new string with first letter capitalized • upper: Returns new string with all letters capitalized • lower: Returns new string with all letters in lower case • Note that original string unchanged • Removing whitespace: • strip: Returns new string with all leading/trailing spaces removed • Example: “ Hi world “.strip() “Hi world”
Example: User-friendly Validation • Goal: Have user enter either “U” or “L” (Assignment 4) • Goal: Be as flexible as possible • Also accept “u” or “l” • Accept those choices with extra spaces (such as “ U “) • Solution: • Use strip to remove extra spaces from user input • Use upper to convert user response to upper case • Then do comparisons
Strings and Search • Main questions: • Does a given string contain some substring? • If so, at what index? • How many instances does it contain? • Where is the first? The last? The Nth? • Automatically replacingall with another string • Shortcut syntax: substring in string • Evaluates to True if string contains substring
Example: Search for Validation • Goal: Force user to enter a legal month abbreviation • month = input(“Enter month in 3-letter: “) • One solution: 12-part condition over all abbreviations • while month != “Jan” and month != “Feb”… • Search-based solution: • Create big string listing all month abbreviations • Check whether user input is a substring of that string • Not completely foolproof!
The find Method for Strings string.find(substring) • Returns the index of the first instance of substring in string • Returns -1 if substringnot in string • Examples for word = “abracadabra” • word.find(“cad”) 4 • word.find(“br”) 1 • word.find(“rad”) -1
Example: Bond, James Bond • Given string in form firstnamelastname • Print in form lastname, firstnamelastname • If just lastname print in form lastname, justlastname • Strategy: • Search for index of space • Use slicing to get lastname as all characters from that index to the end of the string • If no space in the string print in alternative form
Variations on the findMethod • Variations: • string.find(substring, start)Start the search from the index start • word.find(“br”, 3) 8 • string.rfind(substring)Search backwards from the end of the string • word.rfind(“br”) 8
Example: Bond, James Bond • Problem: User may enter more than 2 names • Solution: Search backwards for last space in string
Searching for All Instances • Sometimes need to find all instances of a substring • Idea: Use string.find(substring, start)and loopusing increasing values of start • Initially start = 0 • Use find to get index of next location • Set start to be that index + 1 so next search starts past that location • Continue until findgives -1
String Formatting • Basic formatmethod: • Applied to string containing “placeholders” {} • Arguments are values to “fill in” to those placeholders • ithargument substituted for ithset of {}’s • stringwith{}s.format(arguments)
String Formatting • Example: first = “James” last = “Bond” bond = “{}, {} {}.format(last, first, last) “Bond, James Bond”
String Formatting • Can set formatof how contents of each {}printed • General structure:{:alignmentminwidth.precision type} • Alignment: right, left, or center • Min width: Extra spaces added to fill in that width • Precision: Number of digits after decimal for floats • Type: Printed as string, integer, float, exponent, or percentage
String Alignment • Alignment options: < left> right^ center • Extra spaces up to minimum width added based on alignment • left justification spaces to right • right justification spaces to left • center justification spaces on both side
String Alignment • Example: Creating table header with strings centered over columns 8 chars wide
String Types • Defines how value is printed: s print as string (default) dprint as integer fprint as float(with digits after decimal) eprint in exponential format %print as percentage(multiplying by 100)
Decimal Formatting • For floats can specify number of decimals printed • Syntax: minwidth.precision • Note extra spaces = minwidth- digits before decimal - precision - 1 (for the decimal point) • Uses rounding to get to that precision