Module 4
Module 4
• In this chapter ---see how to access the characters that make up a string ----
learn about some of the methods strings
• A String Is a Sequence
• You can access---- the characters one at a time---with the bracket operator:
• The second statement----- selects character number 1 from fruit and assigns it to
letter.
• The index indicates---- which character in the sequence you want (hence the name).
• But you might not get what you expect:
• >>> letter
• 'a'
• >>> letter
• 'b'
• So b---- the 0th letter ----of 'banana', a ---- the 1st letter and n -----2th letter
• As an index, you can use an expression that contains variables and operators:
• >>> i = 1
• >>> fruit[i]
• 'a'
• >>> fruit[i+1]
• 'n'
• But the value of the index has to be an integer. Otherwise you get:
• >>> s[0:5]
• 'Monty'
• >>> s[6:12]
• 'Python'
• The operator [n:m] returns the part of the string----- from the “n-eth”
character to the “m-eth” character
• If you omit the second index, the slice goes to the end of the string:
• >>> fruit[:3]
• 'ban'
• >>> fruit[3:]
• 'ana'
• If the first index---- is greater than or equal to the second----- the result is an
empty string-----represented by two quotation marks:
• fruit = 'banana'
• >>> fruit[3:3]
• ''
• Continuing this example, what do you think fruit[:] means? Try it and see.
• Strings Are Immutable(not change)
• It is tempting to use the [] operator on the left side of an assignment, ----- the
intention of changing a character in a string.
• For example:
• The reason for the error -----strings are immutable----- which means you can’t change an
existing string.
• >>> new_greeting
• 'Jello, world!’
• A method is similar to a function—it takes arguments and returns a value—but the syntax is
different.
• For example----- the method upper -------takes a string and returns a new string with all uppercase
letters.
• Instead of the function syntax upper(word), it uses the method syntax word.upper():
• >>> new_word
• 'BANANA'
• The empty parentheses----- indicate------ that this method takes no arguments.
• >>> index
•1
• Actually---- the find method is------- more general than our function;
• >>> word.find('na')
•2
• By default---- find starts at the beginning of the string, but it can take a second
arguement, the index where it should start:
• >>> word.find('na', 3)
•4
• >>> name.find('b', 1, 2)
• -1
• This search fails ---because b does not appear----- in the index range from 1
to 2
• STRING MODULE:PYTHON ARRAY
• The string module----- provides a collection of constants and classes for dealing with
strings of characters.
• However------ if you're looking to work------ with arrays of characters (i.e., strings), you
would typically use the built-in list data type.
• Here's a brief overview of the string module and how you might use it alongside arrays:
• import string
• print(string.digits)
• print(string.ascii_letters)
• print(string.punctuation)
• char_array = list(my_string)
• print(char_array)