UMich Python T6.1
UMich Python T6.1
Strings
Chapter 6
len Function (1 of 2)
>>> fruit = 'banana' A function is some stored
>>> x = len(fruit) code that we use. A
>>> print(x) function takes some
6 input and produces an
output.
'banana' len() 6
(a string) function (a number)
PYTHON FOR
Strings – Part 1 EVERYBODY
len Function (2 of 2)
>>> fruit = 'banana' A function is some stored
>>> x = len(fruit) code that we use. A
>>> print(x) function takes some
6 input and produces an
output.
def len(inp):
blah
'banana' blah 6
for x in y:
(a string) blah
(a number)
blah
PYTHON FOR
Strings – Part 1 EVERYBODY
Yes No b a n a n a
Done? Advance letter
print(letter)
The iteration variable “iterates” through the string and the block (body)
of code is executed once for each value in the sequence
PYTHON FOR
Strings – Part 1 EVERYBODY
Slicing Strings
M o n t y P y t h o n
(1 of 2)
• We can also look at any 0 1 2 3 4 5 6 7 8 9 10 11
continuous section of a string >>> s = 'Monty Python'
using a colon operator
>>> print(s[0:4])
• The second number is one Mont
beyond the end of the slice - >>> print(s[6:7])
“up to but not including” P
>>> print(s[6:20])
• If the second number is Python
beyond the end of the string,
it stops at the end
PYTHON FOR
Strings – Part 1 EVERYBODY
Slicing Strings
M o n t y P y t h o n
(2 of 2) 0 1 2 3 4 5 6 7 8 9 10 11
If we leave off the first number or >>> s = 'Monty Python'
the last number of the slice, it is >>> print(s[:2])
assumed to be the beginning or Mo
end of the string respectively >>> print(s[8:])
thon
>>> print(s[:])
Monty Python
PYTHON FOR
Strings – Part 1 EVERYBODY
Manipulating Strings..
PYTHON FOR
Strings – Part 1 EVERYBODY
Acknowledgements / Contributions
These slides are Copyright 2010- Charles R. Severance
(www.dr-chuck.com) of the University of Michigan School of
Information and open.umich.edu and made available under a
Creative Commons Attribution 4.0 License. Please maintain this
last slide in all copies of the document to comply with the
attribution requirements of the license. If you make a change,
feel free to add your name and organization to the list of
contributors on this page as you republish the materials.