SlideShare a Scribd company logo
Creative Commons License
This work is licensed under a Creative Commons Attribution 4.0 International License.
BS GIS Instructor: Inzamam Baig
Lecture 6
Fundamentals of Programming
Strings
A string is a sequence of characters. You can access the characters
one at a time with the bracket operator
>>> fruit = 'apple'
>>> letter = fruit[1]
The second statement extracts the character at index position 1 from
the fruit variable and assigns it to the letter variable
The expression in brackets is called an index
>>> fruit = 'apple'
>>> letter = fruit[1]
>>> print(letter)
p
in Python, the index is an offset from the beginning of the string, and the offset of the first
letter is zero
>>> fruit = 'apple'
>>> letter = fruit[0]
>>> print(letter)
a
>>> letter = fruit[1.5]
TypeError: string indices must be integers
a p p l e
0 1 2 3 4
Index Number
len
len is a built-in function that returns the number of characters in a
string
>>> fruit = 'apple'
>>>len(fruit)
5
>>> length = len(fruit)
>>> last = fruit[length]
IndexError: string index out of range
>>> length = len(fruit)
>>> last = fruit[length-1]
e
Negative Indexing
>>> fruit[-1]
e
a p p l e
-5 -4 -3 -2 -1
Index Number
Traversal through a string with a loop
fruit = 'apple'
index = 0
while index < len(fruit):
letter = fruit[index]
print(letter)
index = index + 1
Traversal through a string with a loop
fruit = 'apple'
for char in fruit:
print(char)
String slices
A segment of a string is called a slice. Selecting a slice is similar
to selecting a character
s = 'Pythonista'
print(s[0:6])
Python
print(s[6:12])
ista
>>> fruit = 'apple'
>>> fruit[:3]
app
>>> fruit[3:]
le
>>> fruit = 'apple'
>>> fruit[3:3]
If the first index is greater than or equal to the second the result
is an empty string
Strings
Strings are immutable
It is tempting to use the operator on the left side of an assignment,
with the intention of changing a character in a string
>>> greeting = 'Hello, world!'
>>> greeting[0] = 'J'
TypeError: 'str' object does not support item assignment
>>> greeting = 'Hello, world!'
>>> new_greeting = 'J' + greeting[1:]
>>> print(new_greeting)
Jello, world!
Looping and Counting
The following program counts the number of times the letter "a"
appears in a string
word = 'apple'
count = 0
for letter in word:
if letter == 'p':
count = count + 1
print(count)
The in operator
The word in is a boolean operator that takes two strings and
returns True if the first appears as a substring in the second
>>> 'a' in 'apple'
True
>>> 'seed' in 'apple'
False
String comparison
if word == 'apple':
print('Word Found.')
if word < 'apple':
print('Your word,' + word + ', comes before
apple.')
elif word > 'apple':
print('Your word,' + word + ', comes after
apple.')
else:
print('All right, apples.')
String Methods
Strings are an example of Python objects.
An object contains both data (the actual string itself) and methods,
which are effectively functions that are built into the object and are
available to any instance of the object
Python has a function called dir which lists the methods available for
an object
The type function shows the type of an object and the dir function
shows the available methods
>>> stuff = 'Hello world'
>>> type(stuff)
>>> dir(stuff)
['capitalize', 'casefold', 'center', 'count',
'encode', 'endswith' , 'expandtabs', 'find',
'format', 'format_map', 'index' , 'isalnum',
'isalpha', 'isdecimal', 'isdigit', 'isidentifier' ,
'islower', 'isnumeric', 'isprintable', 'isspace' ,
'istitle', 'isupper', 'join', 'ljust', 'lower',
'lstrip' , 'maketrans', 'partition', 'replace',
'rfind', 'rindex' , 'rjust', 'rpartition', 'rsplit',
'rstrip', 'split' , 'splitlines', 'startswith',
'strip', 'swapcase', 'title' , 'translate', 'upper',
'zfill']
>>> help(str.capitalize)
Help on method_descriptor: capitalize(...)
S.capitalize() -> str Return a capitalized version
of S, i.e. make the first character have upper case
and the rest lower case.
>>>
>>> word = 'apple'
>>> new_word = word.upper()
>>> print(new_word)
APPLE
A method call is called an invocompute scienceion; in this case,
we would say that we are invoking upper on the word
Find
>>> word = 'apple'
>>> index = word.find('a')
>>> print(index)
0
The find method can find substrings as well as characters:
>>> word.find('le')
3
It can take as a second argument the index where it should start:
>>> word.find('p', 2)
2
White Space Removal
One common task is to remove white space (spaces, tabs, or
newlines) from the beginning and end of a string using the strip
method
>>> line = ' Here we go '
>>> line.strip()
Startwiths
>>> line = 'Have a nice day'
>>> line.startswith('Have')
True
>>> line.startswith('h')
False
Lower and Upper
>>> line.lower()
'have a nice day'
>>> line.upper()
'HAVE A NICE DAY'
Parsing Strings
Often, we want to look into a string and find a substring
From adnan@kiu.edu.pk Sat Jan 5 09:14:16 2008
and we wanted to pull out only the second half of the address
(i.e., kiu.edu.pk) from each line
we can do this by using the find method and string slicing
>>> data = 'From adnan@kiu.edu.pk Sat Jan 5 09:14:16 2008'
>>> at_position = data.find('@')
>>> print(at_position)
10
>>> space_position = data.find(' ',at_position)
>>> print(space_position)
21
>>> host = data[at_position+1:space_position]
>>> print(host)
kiu.edu.pk
>>>
First, we will find the position of the at-sign in the string
Then we will find the position of the first space after the at-sign
And then we will use string slicing to extract the portion of the
string which we are looking for
Format Operator
The format operator, % allows us to construct strings, replacing
parts of the strings with the data stored in variables
>>> number = 42
>>> '%d' % number
42
>>> dollars = 42
>>> 'I have spotted %d dollars.' % dollars
'I have spotted 42 dollars.'
>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'dollars')
>>> '%d %d %d' % (1, 2)
TypeError: not enough arguments for format string
>>> '%d' % 'dollars'
TypeError: %d format: a number is required, not str
String format()
The format() reads the type of arguments passed to it and
formats it according to the format codes defined in the string
# default arguments
print("Department {}, Field {}.".format("Computer
Science", "GIS"))
# positional arguments
print("Field {1}, Department {0}.".format("Computer
Science", "GIS"))
# keyword arguments
print("Department {depart}, Field
{field}.".format(depart = "Computer Science", field
= "GIS"))
# mixed arguments
print("Department {depart}, Field
{0}.".format("GIS", depart = "Computer Science"))
Number Formatting
Number Formatting Types
Type Meaning
d Decimal integer
c Corresponding Unicode character
b Binary format
o Octal format
x Hexadecimal format (lower case)
X Hexadecimal format (upper case)
n Same as 'd'. Except it uses current locale setting for number separator
e Exponential notation. (lowercase e)
E Exponential notation (uppercase E)
f Displays fixed point number (Default: 6)
F Same as 'f'. Except displays 'inf' as 'INF' and 'nan' as 'NAN'
g General format. Rounds number to p significant digits. (Default precision: 6)
G Same as 'g'. Except switches to 'E' if the number is large.
% Percentage. Multiples by 100 and puts % at the end.
# integer arguments
print("Decimal number:{:d}".format(123))
# float arguments
print("Floating point number:{:.2f}".format(123.4567898))
# octal, binary and hexadecimal format
print("Binary: {0:b}, Octal: {0:o}, Hexadecimal:
{0:x}".format(12))
Number Formatting
# integer numbers with minimum width
print("{:5d}".format(12))
# width doesn't work for numbers longer than padding
print("{:2d}".format(1234))
# padding for float numbers
print("{:8.3f}".format(12.2346))
# integer numbers with minimum width filled with
zeros
print("{:05d}".format(12))
# padding for float numbers filled with zeros
print("{:08.3f}".format(12.2346))
Number formatting with alignment
Type Meaning
< Left aligned to the remaining space
^ Center aligned to the remaining space
> Right aligned to the remaining space
= Forces the signed (+) (-) to the leftmost position
# integer numbers with right alignment
print("{:>5d}".format(12))
# float numbers with center alignment
print("{:^10.3f}".format(12.2346))
# integer left alignment filled with zeros
print("{:<05d}".format(12))
# float numbers with center alignment
print("{:=8.3f}".format(-12.2346))

More Related Content

PPTX
Python Datatypes by SujithKumar
PPT
Python study material
PPTX
Python language data types
PPTX
Python programming lab3 250215
PDF
Datatypes in python
PPT
Python course in_mumbai
PPTX
Datastructures in python
Python Datatypes by SujithKumar
Python study material
Python language data types
Python programming lab3 250215
Datatypes in python
Python course in_mumbai
Datastructures in python

What's hot (19)

PDF
Strings in Python
PPTX
Standard data-types-in-py
PPTX
Computer programming 2 Lesson 12
PPT
Introduction to Python Language and Data Types
PPTX
Arrays
PDF
Strings IN C
PDF
Python programming : Strings
PPTX
Basics of Python
PPT
Pythonintroduction
PPTX
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
PPTX
Sequence Types in Python Programming
PDF
Python Modules, Packages and Libraries
PDF
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
PPTX
Chapter 14 strings
PPTX
Python Modules and Libraries
PDF
05 c++-strings
Strings in Python
Standard data-types-in-py
Computer programming 2 Lesson 12
Introduction to Python Language and Data Types
Arrays
Strings IN C
Python programming : Strings
Basics of Python
Pythonintroduction
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
Sequence Types in Python Programming
Python Modules, Packages and Libraries
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
Chapter 14 strings
Python Modules and Libraries
05 c++-strings
Ad

Similar to Python Lecture 6 (20)

PPTX
Strings.pptx
PPTX
DATA TYPES IN PYTHON jesjdjdjkdkkdk.pptx
PPTX
Python String Revisited.pptx
PPTX
Lexture about strings, all examples and theoretical part is included
PPTX
Python Strings and its Featues Explained in Detail .pptx
PDF
Python data handling
PDF
Strings brief introduction in python.pdf
PPTX
Day5 String python language for btech.pptx
PPTX
Introduction To Programming with Python-3
PPTX
Python Programming-UNIT-II - Strings.pptx
PPT
PPS_Unit 4.ppt
PDF
Python- strings
PPTX
Strings.pptxbfffffffffffffffffffffffffffffffffffffffffd
PDF
python1uhaibueuhERADGAIUSAERUGHw9uSS.pdf
PPTX
Python chapter 2
PPTX
python chapter 1
PPTX
Python Strings.pptx
PPTX
varthini python .pptx
PPTX
trisha comp ppt.pptx
PDF
Learn 90% of Python in 90 Minutes
Strings.pptx
DATA TYPES IN PYTHON jesjdjdjkdkkdk.pptx
Python String Revisited.pptx
Lexture about strings, all examples and theoretical part is included
Python Strings and its Featues Explained in Detail .pptx
Python data handling
Strings brief introduction in python.pdf
Day5 String python language for btech.pptx
Introduction To Programming with Python-3
Python Programming-UNIT-II - Strings.pptx
PPS_Unit 4.ppt
Python- strings
Strings.pptxbfffffffffffffffffffffffffffffffffffffffffd
python1uhaibueuhERADGAIUSAERUGHw9uSS.pdf
Python chapter 2
python chapter 1
Python Strings.pptx
varthini python .pptx
trisha comp ppt.pptx
Learn 90% of Python in 90 Minutes
Ad

More from Inzamam Baig (13)

PPTX
Python Lecture 8
PPTX
Python Lecture 13
PPTX
Python Lecture 12
PPTX
Python Lecture 11
PPTX
Python Lecture 10
PPTX
Python Lecture 9
PPTX
Python Lecture 7
PPTX
Python Lecture 5
PPTX
Python Lecture 4
PPTX
Python Lecture 3
PPTX
Python Lecture 2
PPTX
Python Lecture 1
PPTX
Python Lecture 0
Python Lecture 8
Python Lecture 13
Python Lecture 12
Python Lecture 11
Python Lecture 10
Python Lecture 9
Python Lecture 7
Python Lecture 5
Python Lecture 4
Python Lecture 3
Python Lecture 2
Python Lecture 1
Python Lecture 0

Recently uploaded (20)

PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Computing-Curriculum for Schools in Ghana
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
01-Introduction-to-Information-Management.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Cell Types and Its function , kingdom of life
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
Complications of Minimal Access Surgery at WLH
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Microbial diseases, their pathogenesis and prophylaxis
Supply Chain Operations Speaking Notes -ICLT Program
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Computing-Curriculum for Schools in Ghana
202450812 BayCHI UCSC-SV 20250812 v17.pptx
01-Introduction-to-Information-Management.pdf
O7-L3 Supply Chain Operations - ICLT Program
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Cell Types and Its function , kingdom of life
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Complications of Minimal Access Surgery at WLH
Final Presentation General Medicine 03-08-2024.pptx
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Chinmaya Tiranga quiz Grand Finale.pdf
102 student loan defaulters named and shamed – Is someone you know on the list?
Anesthesia in Laparoscopic Surgery in India
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Abdominal Access Techniques with Prof. Dr. R K Mishra
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf

Python Lecture 6

  • 1. Creative Commons License This work is licensed under a Creative Commons Attribution 4.0 International License. BS GIS Instructor: Inzamam Baig Lecture 6 Fundamentals of Programming
  • 2. Strings A string is a sequence of characters. You can access the characters one at a time with the bracket operator >>> fruit = 'apple' >>> letter = fruit[1] The second statement extracts the character at index position 1 from the fruit variable and assigns it to the letter variable The expression in brackets is called an index
  • 3. >>> fruit = 'apple' >>> letter = fruit[1] >>> print(letter) p in Python, the index is an offset from the beginning of the string, and the offset of the first letter is zero >>> fruit = 'apple' >>> letter = fruit[0] >>> print(letter) a
  • 4. >>> letter = fruit[1.5] TypeError: string indices must be integers a p p l e 0 1 2 3 4 Index Number
  • 5. len len is a built-in function that returns the number of characters in a string >>> fruit = 'apple' >>>len(fruit) 5
  • 6. >>> length = len(fruit) >>> last = fruit[length] IndexError: string index out of range
  • 7. >>> length = len(fruit) >>> last = fruit[length-1] e
  • 8. Negative Indexing >>> fruit[-1] e a p p l e -5 -4 -3 -2 -1 Index Number
  • 9. Traversal through a string with a loop fruit = 'apple' index = 0 while index < len(fruit): letter = fruit[index] print(letter) index = index + 1
  • 10. Traversal through a string with a loop fruit = 'apple' for char in fruit: print(char)
  • 11. String slices A segment of a string is called a slice. Selecting a slice is similar to selecting a character s = 'Pythonista' print(s[0:6]) Python print(s[6:12]) ista
  • 12. >>> fruit = 'apple' >>> fruit[:3] app >>> fruit[3:] le
  • 13. >>> fruit = 'apple' >>> fruit[3:3] If the first index is greater than or equal to the second the result is an empty string
  • 14. Strings Strings are immutable It is tempting to use the operator on the left side of an assignment, with the intention of changing a character in a string >>> greeting = 'Hello, world!' >>> greeting[0] = 'J' TypeError: 'str' object does not support item assignment
  • 15. >>> greeting = 'Hello, world!' >>> new_greeting = 'J' + greeting[1:] >>> print(new_greeting) Jello, world!
  • 16. Looping and Counting The following program counts the number of times the letter "a" appears in a string word = 'apple' count = 0 for letter in word: if letter == 'p': count = count + 1 print(count)
  • 17. The in operator The word in is a boolean operator that takes two strings and returns True if the first appears as a substring in the second >>> 'a' in 'apple' True >>> 'seed' in 'apple' False
  • 18. String comparison if word == 'apple': print('Word Found.')
  • 19. if word < 'apple': print('Your word,' + word + ', comes before apple.') elif word > 'apple': print('Your word,' + word + ', comes after apple.') else: print('All right, apples.')
  • 20. String Methods Strings are an example of Python objects. An object contains both data (the actual string itself) and methods, which are effectively functions that are built into the object and are available to any instance of the object Python has a function called dir which lists the methods available for an object The type function shows the type of an object and the dir function shows the available methods
  • 21. >>> stuff = 'Hello world' >>> type(stuff)
  • 22. >>> dir(stuff) ['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith' , 'expandtabs', 'find', 'format', 'format_map', 'index' , 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier' , 'islower', 'isnumeric', 'isprintable', 'isspace' , 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip' , 'maketrans', 'partition', 'replace', 'rfind', 'rindex' , 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split' , 'splitlines', 'startswith', 'strip', 'swapcase', 'title' , 'translate', 'upper', 'zfill']
  • 23. >>> help(str.capitalize) Help on method_descriptor: capitalize(...) S.capitalize() -> str Return a capitalized version of S, i.e. make the first character have upper case and the rest lower case. >>>
  • 24. >>> word = 'apple' >>> new_word = word.upper() >>> print(new_word) APPLE
  • 25. A method call is called an invocompute scienceion; in this case, we would say that we are invoking upper on the word
  • 26. Find >>> word = 'apple' >>> index = word.find('a') >>> print(index) 0
  • 27. The find method can find substrings as well as characters: >>> word.find('le') 3 It can take as a second argument the index where it should start: >>> word.find('p', 2) 2
  • 28. White Space Removal One common task is to remove white space (spaces, tabs, or newlines) from the beginning and end of a string using the strip method >>> line = ' Here we go ' >>> line.strip()
  • 29. Startwiths >>> line = 'Have a nice day' >>> line.startswith('Have') True >>> line.startswith('h') False
  • 30. Lower and Upper >>> line.lower() 'have a nice day' >>> line.upper() 'HAVE A NICE DAY'
  • 31. Parsing Strings Often, we want to look into a string and find a substring From [email protected] Sat Jan 5 09:14:16 2008 and we wanted to pull out only the second half of the address (i.e., kiu.edu.pk) from each line we can do this by using the find method and string slicing
  • 32. >>> data = 'From [email protected] Sat Jan 5 09:14:16 2008' >>> at_position = data.find('@') >>> print(at_position) 10 >>> space_position = data.find(' ',at_position) >>> print(space_position) 21 >>> host = data[at_position+1:space_position] >>> print(host) kiu.edu.pk >>>
  • 33. First, we will find the position of the at-sign in the string Then we will find the position of the first space after the at-sign And then we will use string slicing to extract the portion of the string which we are looking for
  • 34. Format Operator The format operator, % allows us to construct strings, replacing parts of the strings with the data stored in variables >>> number = 42 >>> '%d' % number 42 >>> dollars = 42 >>> 'I have spotted %d dollars.' % dollars 'I have spotted 42 dollars.'
  • 35. >>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'dollars')
  • 36. >>> '%d %d %d' % (1, 2) TypeError: not enough arguments for format string >>> '%d' % 'dollars' TypeError: %d format: a number is required, not str
  • 37. String format() The format() reads the type of arguments passed to it and formats it according to the format codes defined in the string # default arguments print("Department {}, Field {}.".format("Computer Science", "GIS"))
  • 38. # positional arguments print("Field {1}, Department {0}.".format("Computer Science", "GIS"))
  • 39. # keyword arguments print("Department {depart}, Field {field}.".format(depart = "Computer Science", field = "GIS"))
  • 40. # mixed arguments print("Department {depart}, Field {0}.".format("GIS", depart = "Computer Science"))
  • 41. Number Formatting Number Formatting Types Type Meaning d Decimal integer c Corresponding Unicode character b Binary format o Octal format x Hexadecimal format (lower case) X Hexadecimal format (upper case) n Same as 'd'. Except it uses current locale setting for number separator e Exponential notation. (lowercase e) E Exponential notation (uppercase E) f Displays fixed point number (Default: 6) F Same as 'f'. Except displays 'inf' as 'INF' and 'nan' as 'NAN' g General format. Rounds number to p significant digits. (Default precision: 6) G Same as 'g'. Except switches to 'E' if the number is large. % Percentage. Multiples by 100 and puts % at the end.
  • 42. # integer arguments print("Decimal number:{:d}".format(123)) # float arguments print("Floating point number:{:.2f}".format(123.4567898)) # octal, binary and hexadecimal format print("Binary: {0:b}, Octal: {0:o}, Hexadecimal: {0:x}".format(12))
  • 43. Number Formatting # integer numbers with minimum width print("{:5d}".format(12)) # width doesn't work for numbers longer than padding print("{:2d}".format(1234)) # padding for float numbers print("{:8.3f}".format(12.2346))
  • 44. # integer numbers with minimum width filled with zeros print("{:05d}".format(12)) # padding for float numbers filled with zeros print("{:08.3f}".format(12.2346))
  • 45. Number formatting with alignment Type Meaning < Left aligned to the remaining space ^ Center aligned to the remaining space > Right aligned to the remaining space = Forces the signed (+) (-) to the leftmost position
  • 46. # integer numbers with right alignment print("{:>5d}".format(12)) # float numbers with center alignment print("{:^10.3f}".format(12.2346)) # integer left alignment filled with zeros print("{:<05d}".format(12)) # float numbers with center alignment print("{:=8.3f}".format(-12.2346))

Editor's Notes

  • #7: To get the last letter of a string, you might be tempted to try something like this The reason for the IndexError is that there is no letter in "apple" with the index 6. Since we started counting at zero, the six letters are numbered 0 to 5. To get the last character, you have to subtract 1 from length
  • #9: Alternatively, you can use negative indices, which count backward from the end of the string. The expression fruit[-1] yields the last letter, fruit[-2] yields the second to last, and so on
  • #10: This loop traverses the string and displays each letter on a line by itself. The loop condition is index < len(fruit), so when index is equal to the length of the string, the condition is false, and the body of the loop is not executed. The last character accessed is the one with the index len(fruit)-1, which is the last character in the string
  • #11: Each time through the loop, the next character in the string is assigned to the variable char. The loop continues until no characters are left
  • #14: An empty string contains no characters and has length 0, but other than that, it is the same as any other string
  • #15: For now, an object is the same thing as a value, but we will refine that definition late. The reason for the error is that strings are immutable, which means you can't change an existing string
  • #20: Python does not handle uppercase and lowercase letters the same way that people do. All the uppercase letters come before all the lowercase letters
  • #23: dir function lists the methods
  • #24: you can use help to get some simple documentation on a method
  • #25: This form of dot notation specifies the name of the method, upper, and the name of the string to apply the method to, word. The empty parentheses indicompute sciencee that this method takes no argument
  • #26: In this example, we invoke find on word and pass the letter we are looking for as a parameter
  • #30: startswith requires case to match
  • #35: the format sequence %d means that the second operand should be formatted as an integer ("d" stands for "decimal")
  • #36: If there is more than one format sequence in the string, the second argument has to be a tuple. The following example uses %d to format an integer, %g to format a floating-point number and %s to format a string
  • #37: The number of elements in the tuple must match the number of format sequences in the string. The types of the elements also must match the format sequences In the first example, there aren't enough elements; in the second, the element is the wrong type