1 / 25

String Methods

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.

tien
Télécharger la présentation

String Methods

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. String Methods CSIS 1595: Fundamentals of Programming and Problem Solving 1

  2. 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

  3. 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

  4. String Methods • Comprehensive list at http://docs.python.org/3.3/library/stdtypes.html#string-methods • General categories: • Search • Formatting • Modification (capitalizing, etc.) • Etc.

  5. 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”

  6. 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

  7. Example: User-friendly Validation

  8. 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

  9. 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!

  10. Example: Search for Validation

  11. 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

  12. 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

  13. Example: Bond, James Bond

  14. 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

  15. Example: Bond, James Bond • Problem: User may enter more than 2 names • Solution: Search backwards for last space in string

  16. 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

  17. Searching for All Instances

  18. 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)

  19. String Formatting • Example: first = “James” last = “Bond” bond = “{}, {} {}.format(last, first, last) “Bond, James Bond”

  20. 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

  21. 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

  22. String Alignment • Example: Creating table header with strings centered over columns 8 chars wide

  23. 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)

  24. 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

  25. Example: Square, Square Root Table

More Related