Strings: Python For Informatics: Exploring Information
Strings: Python For Informatics: Exploring Information
Chapter 6
b a n a n a
• There is a built-in function len that
0 1 2 3 4 5
gives us the length of a string
'banana' len() 6
(a number)
(a string) function
•
fruit = 'banana'
A definite loop using a for for letter in fruit : b
statement is much more print letter a
elegant n
a
• The iteration variable is index = 0 n
completely taken care of by while index < len(fruit) :
a
the for loop letter = fruit[index]
print letter
index = index + 1
Looping and Counting
print letter
The iteration variable “iterates” through the string and the block
(body) of code is executed once for each value in the sequence
M o n t y P y t h o n
0 1 2 3 4 5 6 7 8 9 10 11
• We can also look at any
continuous section of a string >>> s = 'Monty Python'
using a colon operator >>> print s[0:4]
Mont
• The second number is one >>> print s[6:7]
beyond the end of the slice - P
“up to but not including”
>>> print s[6:20]
• If the second number is Python
beyond the end of the string, it
stops at the end
Slicing Strings
M o n t y P y t h o n
0 1 2 3 4 5 6 7 8 9 10 11
Slicing Strings
String Concatenation
>>> a = 'Hello'
• When the + operator is >>> b = a + 'There'
>>> print b
applied to strings, it
means “concatenation” HelloThere
>>> c = a + ' ' + 'There'
>>> print c
Hello There
>>>
Using in as a logical Operator
• The in keyword can also be
>>> fruit = 'banana'
>>> 'n' in fruit
used to check to see if one True
string is “in” another string >>> 'm' in fruit
False
• The in expression is a >>> 'nan' in fruit
True
logical expression that
>>> if 'a' in fruit :
returns True or False and ... print 'Found it!'
can be used in an if ...
statement Found it!
>>>
String Comparison
if word == 'banana':
print 'All right, bananas.'
https://docs.python.org/2/library/stdtypes.html#string-methods
String Library