Strings: Python For Everybody
Strings: Python For Everybody
Chapter 6
Converting Enter:Chuck
>>> print(name)
Chuck
• We prefer to read data in using >>> apple = input('Enter:')
strings and then parse and Enter:100
convert the data as we need >>> x = apple – 10
Traceback (most recent call last): File
• This gives us more control over "<stdin>", line 1, in <module>
error situations and/or bad user TypeError: unsupported operand type(s) for -:
input 'str' and 'int'
>>> x = int(apple) – 10
• Input numbers must be >>> print(x)
converted from strings 90
Looking Inside Strings
• We can get at any single character in a b a n a n a
string using an index specified in 0 1 2 3 4 5
square brackets
>>> fruit = 'banana'
• So be careful when
>>> print(zot[5])
Traceback (most recent call last): File
constructing index values "<stdin>", line 1, in <module>
and slices IndexError: string index out of range
>>>
• Not to confuse this with an
empty range in case of
slicing
Strings Have Length
b a n a n a
The built-in function len gives 0 1 2 3 4 5
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
6 input and produces an
output.
'banana' len() 6
(a number)
(a string) function
len Function
>>> 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 number)
(a string) blah
blah
Looping Through Strings
print(letter)
The iteration variable “iterates” through the string and the block (body)
of code is executed once for each value in the sequence
More String Operations
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
• We can also look at any
continuous section of a string
using a colon operator >>> s = 'Monty Python'
>>> 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
• If the second number is >>> print(s[6:20])
beyond the end of the string, Python
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
https://docs.python.org/3/library/stdtypes.html#string-methods
String Library
str.capitalize() str.replace(old, new[, count])
str.center(width[, fillchar]) str.lower()
str.endswith(suffix[, start[, end]]) str.rstrip([chars])
str.find(sub[, start[, end]]) str.strip([chars])
str.lstrip([chars]) str.upper()
Searching a String
b a n a n a
• We use the find() function to search
for a substring within another string
0 1 2 3 4 5