0% found this document useful (0 votes)
49 views31 pages

Strings: Python For Informatics: Exploring Information

The document discusses strings in Python including defining strings with quotes, concatenating strings with the + operator, accessing characters within a string using indexes, determining the length of a string with len, looping through strings, slicing strings, comparing strings, and checking if a substring is contained within a string using the in operator.

Uploaded by

sumanth
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views31 pages

Strings: Python For Informatics: Exploring Information

The document discusses strings in Python including defining strings with quotes, concatenating strings with the + operator, accessing characters within a string using indexes, determining the length of a string with len, looping through strings, slicing strings, comparing strings, and checking if a substring is contained within a string using the in operator.

Uploaded by

sumanth
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 31

Strings

Chapter 6

Python for Informatics: Exploring Information


www.pythonlearn.com
Unless otherwise noted, the content of this course material is licensed under a Creative
Commons Attribution 3.0 License.
http://creativecommons.org/licenses/by/3.0/.

Copyright 2010- Charles Severance


String Data >>> str1 = "Hello”
>>> str2 = 'there'
• A string isType
a sequence of >>> bob = str1 + str2
characters >>> print bob
• A string literal uses quotes
Hellothere
>>> str3 = '123'
'Hello' or “Hello” >>> str3 = str3 + 1
• For strings, + means
Traceback (most recent call last):
File "<stdin>", line 1, in
“concatenate”
<module>TypeError: cannot
• When a string contains concatenate 'str' and 'int' objects
numbers, it is still a string >>> x = int(str3) + 1
>>> print x
• We can convert numbers in a 124
string into a number using int() >>>
Reading and >>> name = raw_input('Enter:')
Enter:Chuck
Converting
• We prefer to read data in >>> print name
using strings and then Chuck
parse and convert the >>> apple = raw_input('Enter:')
data as we need Enter:100
>>> x = apple – 10
• This gives us more Traceback (most recent call last):
control over error File "<stdin>", line 1, in
situations and/or bad <module>TypeError: unsupported
user input operand type(s) for -: 'str' and 'int'
>>> x = int(apple) – 10
• Raw input numbers must >>> print x
be converted from 90
strings
Looking Inside Strings
• We can get at any single
b a n a n a
character in a string using an
index specified in square 0 1 2 3 4 5
brackets >>> fruit = 'banana'
>>> letter = fruit[1]
• The index value must be an >>> print letter
integer and starts at zero a
• The index value can be an
>>> n = 3
>>> w = fruit[n - 1]
expression that is computed
>>> print w
n
A Character Too Far

• You will get a python error if >>> zot = 'abc'


>>> print zot[5]
you attempt to index beyond
the end of a string. Traceback (most recent call last):
File "<stdin>", line 1, in
• So be careful when <module>IndexError: string index
constructing index values and out of range
slices >>>
Strings Have Length

b a n a n a
0 1 2 3 4 5
• There is a built-in function len
that gives us the length of a string >>> fruit = 'banana'
>>> print len(fruit)
6
Len Function
A function is some
>>> fruit = 'banana'
stored code that we
>>> x = len(fruit)
use. A function takes
>>> print x
some input and
6
produces an output.

'banana' len() 6
(a string) (a number)
function

Guido wrote this code


Len Function
A function is some
>>> fruit = 'banana'
stored code that we
>>> x = len(fruit)
use. A function takes
>>> print x
some input and
6
produces an output.

def len(inp):
blah
'banana' blah 6
for x in y: (a number)
(a string) blah
blah
Looping Through Strings

• Using a while statement fruit = 'banana' 0b


and an iteration variable, index = 0 1a
and the len function, we can while index < len(fruit) : 2n
construct a loop to look at letter = fruit[index] 3a
each of the letters in a print index, letter 4n
string individually index = index + 1 5a
Looping Through Strings

• A definite loop using a for b


statement is much more a
elegant fruit = 'banana' n
for letter in fruit :
• The iteration variable is print letter
a
n
completely taken care of by a
the for loop
Looping Through Strings
fruit = 'banana'
• A definite loop using a for for letter in fruit : b
statement is much more print letter a
elegant n
• The iteration variable is index = 0 a
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

• This is a simple loop that word = 'banana'


loops through each letter in count = 0
a string and counts the for letter in word :
number of times the loop if letter == 'a' :
encounters the 'a' character. count = count + 1
print count
Looking deeper into in
• The iteration variable
“iterates” though the
sequence (ordered set) Six-character string
Iteration variable
• The block (body) of code
is executed once for
each value in the for letter in 'banana' :
sequence print letter
• The iteration variable
moves through all of the
values in the sequence
Yes b a n a n a
Done? Advance letter

print letter

for letter in 'banana' :


print letter

The iteration variable “iterates” though 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 >>> s = 'Monty Python'
string using a colon >>> print s[0:4]
operator Mont
>>> print s[6:7]
• The second number is one P
beyond the end of the slice >>> print s[6:20]
- “up to but not including” Python

• If the second number is


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

>>> s = 'Monty Python'


>>> print s[:2]
• If we leave off the first Mo
>>> print s[8:]
number or the last number
of the slice, it is assumed to Thon
be the beginning or end of >>> print s[:]
the string respectively Monty Python

Slicing Strings
String Concatenation
>>> a = 'Hello'
>>> b = a + 'There'
>>> print b
• When the + operator is HelloThere
applied to strings, it >>> c = a + ' ' + 'There'
means "concatenation" >>> print c
Hello There
>>>
Using in as an Operator
• The in keyword can also >>> fruit = 'banana’
>>> 'n' in fruit
be used to check to see if
True
one string is "in" another >>> 'm' in fruit
string False
>>> 'nan' in fruit
• The in expression is a True
logical expression and >>> if 'a' in fruit :
... print 'Found it!’
returns True or False and
...
can be used in an if Found it!
statement >>>
String Comparison
if word == 'banana':
print 'All right, bananas.'

if word < 'banana':


print 'Your word,' + word + ', comes before banana.’
elif word > 'banana':
print 'Your word,' + word + ', comes after banana.’
else:
print 'All right, bananas.'
String Library
• Python has a number of string
functions which are in the string
library >>> greet = 'Hello Bob'>>> zap
= greet.lower()>>> print
• These functions are already built zaphello bob
into every string - we invoke them >>> print greet
by appending the function to the Hello Bob>>> print 'Hi
string variable There'.lower()
• These functions do not modify the
hi there
>>>
original string, instead they return
a new string that has been altered
>>> stuff = 'Hello world’
>>> type(stuff)<type 'str'>
>>> dir(stuff)
['capitalize', 'center', 'count', 'decode', 'encode', 'endswith',
'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit',
'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip',
'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit',
'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper', 'zfill']

http://docs.python.org/lib/string-methods.html
http://docs.python.org/lib/string-methods.html
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()

http://docs.python.org/lib/string-methods.html
Searching a
String
• We use the find() function
to search for a substring b a n a n a
within another string 0 1 2 3 4 5
• find() finds the first >>> fruit = 'banana'
occurance of the >>> pos = fruit.find('na')
substring >>> print pos

• If the substring is not


2
>>> aa = fruit.find('z')
found, find() returns -1 >>> print aa
• Remember that string
-1
position starts at zero
Making everything UPPER
CASE
• You can make a copy of a string in
>>> greet = 'Hello Bob'
>>> nnn = greet.upper()
lower case or upper case >>> print nnn
• Often when we are searching for a HELLO BOB
>>> www = greet.lower()
string using find() - we first convert
the string to lower case so we can >>> print www
search a string regardless of case hello bob
>>>
Search and Replace
• The replace()
function is like a
“search and >>> greet = 'Hello Bob'
replace” operation >>> nstr = greet.replace('Bob','Jane')
in a word processor >>> print nstr
Hello Jane
• It replaces all >>> nstr = greet.replace('o','X')
occurrences of the >>> print nstrHellX BXb
search string with >>>
the replacement
string
Stripping Whitespace
• Sometimes we want to take
a string and remove >>> greet = ' Hello Bob '
whitespace at the beginning >>> greet.lstrip()
and/or end 'Hello Bob '
>>> greet.rstrip()
• lstrip() and rstrip() to the left ' Hello Bob'
and right only >>> greet.strip()
'Hello Bob'
• strip() Removes both begin >>>
and ending whitespace
Prefixes

>>> line = 'Please have a nice day’


>>> line.startswith('Please')
True
>>> line.startswith('p')
False
21 31

From [email protected] Sat Jan 5 09:14:16 2008

>>> data = 'From [email protected] Sat Jan 5 09:14:16 2008’


>>> atpos = data.find('@')
>>> print atpos
21
>>> sppos = data.find(' ',atpos)
>>> print sppos
31
>>> host = data[atpos+1 : sppos]
>>> print host Parsing and
uct.ac.za Extracting
Summary
• String type
• Read/Convert
• Indexing strings []
• Slicing strings [2:4]
• Looping through strings with for and while
• Concatenating strings with +
• String operations

You might also like