Professional Documents
Culture Documents
Py4Inf 06 Strings
Py4Inf 06 Strings
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
>>> fruit = 'banana'
>>> print len(fruit)
6
Len Function
>>> fruit = 'banana' A function is some stored
>>> x = len(fruit) code that we use. A
>>> print x function takes some input
6 and produces an output.
'banana' len() 6
(a string) function (a number)
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
HelloThere
means “concatenation”
>>> 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
https://docs.python.org/2/library/stdtypes.html#string-methods
String Library
• It replaces all
>>> print nstr
HellX BXb
occurrences of the >>>
search string with the
replacement string
Stripping Whitespace
• Sometimes we want to take a
string and remove whitespace at >>> greet = ' Hello Bob '
the beginning and/or end >>> greet.lstrip()
'Hello Bob '