0% found this document useful (0 votes)
8 views

ch03-CreatingModifyingText

Chapter 3 covers creating and modifying text in Python, focusing on string manipulation, concatenation, and conversion between data types. It explains the use of quotes for strings, the importance of data types, and demonstrates various string operations including concatenation, multiplication, and indexing. Additionally, it introduces functions for generating MadLib stories and encoding/decoding with a keyword cipher.

Uploaded by

Hasnain
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

ch03-CreatingModifyingText

Chapter 3 covers creating and modifying text in Python, focusing on string manipulation, concatenation, and conversion between data types. It explains the use of quotes for strings, the importance of data types, and demonstrates various string operations including concatenation, multiplication, and indexing. Additionally, it introduces functions for generating MadLib stories and encoding/decoding with a keyword cipher.

Uploaded by

Hasnain
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 60

Chapter 3: Creating and

Modifying Text

© 2016 Pearson Education, Inc., Hoboken, NJ. All


rights reserved.
Chapter Learning Objectives

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


Which of the statements below is true after
these two statements are executed? (Can be
more than one.)

1)Variable a is now empty

2)Variable a is still 10

3)Variable b is now 10

4)If we change variable a again, b will change


© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Strings
Strings are defined with quote marks.
Python actually supports three kinds of
quotes:
>>> print 'this is a string'
this is a string
>>> print "this is a string"
this is a string
>>> print """this is a string"""
this is a string
Use the right one that allows you to embed
quote marks you want
>>> aSingleQuote = " ' "
>>> print aSingleQuote
'
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
What type of data is in the variable
filename after executing this statement?

1)File name

2)Picture

3)String

4)Float
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Triple Quotes allow us to Embed

>>> sillyString()
This is using triple quotes. Why?
Notice the different lines.
And we can't ignore the use of apostrophes.

Because we can do this.


© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Adding strings and numbers:
Not together
>>> print 4 + 5
9
Adding strings
>>> print "4"+"5"
together is
45 called
>>> print 4 + "5" “concatenation
The error was: 'int' and 'str' ”
Inappropriate argument type.

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


Unless you >>> print 4 + 1
5
>>> print str(4) + str(1)
convert 41
>>> print int("4")
4
Using int() and
>>> print int("abc")
float(), you can The error was: abc
convert strings to Inappropriate argument value (of correct
type).
numbers. An error occurred attempting to pass an
If the string is a argument to a function.
valid integer or >>> print float("124.3")
124.3
floating-point >>> print int("124.3")
number. The error was: 124.3
Using str(), you Inappropriate argument value (of correct
type).
can convert An error occurred attempting to pass an
numbers to argument to a function.
strings.
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
This will result in:

1)13

2)An error

3)“12”

4)“121”
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
How could this be?

1)An error because string can’t be


redefined.

2)string is “1.0000000000/3”

3)string is “0.333333333333”

4)©string is “1/3.0000000000”
2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Using string concatenation to
tell a MadLib story

© 2016 Pearson Education, Inc., Hoboken, NJ. All


rights reserved.
Running our MadLib function
>>> madlib()
Once upon a time, Mark was walking with
Baxter, a trained dragon. Suddenly, Baxter
stopped and announced,'I have a desperate
need for Krispy Kreme Doughnuts'.
Mark complained. 'Where I am going to get
that?' Then Mark found a wizard's wand. With
a wave of the wand, Baxter got Krispy Kreme
Doughnuts. Perhaps surprisingly, Baxter ate
the Krispy Kreme Doughnuts.
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights
reserved.
Running new one
>>> madlib2()
Once upon a time, Ty was walking with Fluffy,
a trained dragon. Suddenly, Fluffy stopped and
announced,'I have a desperate need for a
seven-layer wedding cake.'.
Ty complained. 'Where I am going to get that?'
Then Ty found a wizard's wand. With a wave of
the wand, Fluffy got a seven-layer wedding
cake.. Perhaps surprisingly, Fluffy rolled on the
a seven-layer wedding cake.
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Can generate new MadLib stories
without changing program
>>> madlib3("Lee","Spot","stomped on","Taco
Bell nachos")
Once upon a time, Lee was walking with Spot, a
trained dragon. Suddenly, Spot stopped and
announced,'I have a desperate need for Taco
Bell nachos'.
Lee complained. 'Where I am going to get that?'
Then Lee found a wizard's wand. With a wave of
the wand, Spot got Taco Bell nachos. Perhaps
surprisingly, Spot stomped on the Taco Bell
nachos.
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Multiplication is repeated Addition:
Strings, too
>>> print "abc" * 3
Multiplicati
abcabcabc on
>>> print 4 * "Hey!" concatenate
s copies of
Hey!Hey!Hey!Hey!
the string

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
What does this print?

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


Taking strings apart

Read for as “for


>>> parts() each”
H
e “For each letter
in the string…
l print the letter.”
l
o
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
The for loop
The word for has to be there.
Next comes the index variable
that will take on the value of
each element of the collection.
The word in has to be there
The colon (“:”) says, “Next
comes the body of the loop.”
The statements in the body of
the loop must be indented.
Anything can be inside the for
loop
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Using if to test the letters

>>> justvowels("hello there!")


e
o
e
e
© 2016 Pearson Education, Inc., Hoboken, NJ. All
rights reserved.
Using if to
test the
letters >>> notvowels("hello there!")
h
l
l

t
h
r
!
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Two different ways to deal with
case

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


Collecting characters into
strings
>>> word = "Um"
>>> print word
Um
>>> word = word + "m"
>>> print word
Umm
>>> word = word + "m"
>>> print word
Ummm
>>> word = word + "m"
>>> print word
Ummmm
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights
reserved.
Return a new string from
pieces

>>> duplicate("rubber duck")


rubber duck
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
More interesting: Double

>>> double("rubber
duck")
rruubbbbeerr dduucckk
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
More interesting: Reverse

>>> reverse("rubber
duck")
kcud rebbur
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Mirroring
We can add the index variable to both sides of
the pile

© 2016 Pearson Education, Inc., Hoboken, NJ. All


rights reserved.
Two of these “double” programs
produces this:
>>> double_("apple")
aappppllee
Which one doesn’t?

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


Only one of these programs prints more
than one exclamation point.
Which one is it?

def exclaim1(somestring):
target = "!"
for char in somestring:
target = target + char def exclaim2(somestring):
print target target = "!"
for char in somestring:
target = char + target
print target
def exclaim3(somestring):
target = ""
for char in somestring:
target = target + char + "!"
print target © 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
One of these, when you call it with the
input of “Between” will print:
>B<e<t<w<e<e<n<
Which one?
def between1(somestring):
target = ">"
for char in somestring: def between2(somestring):
target = target + char target = "<>"
print target+"<" for char in somestring:
target = char + target + char
print target
def between3(somestring):
target = ">"
for char in somestring:
target = target + char + "<"
print target © 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Creating language patterns
def doubledutch(name):
pile = ""
for letter in name:
if letter.lower() in "aeiou":
pile = pile + letter
if not (letter.lower() in "aeiou"):
pile = pile + letter + "u" + letter
print pile

>>> doubledutch("mark")
mumarurkuk
>>> doubledutch("bill")
bubilullul
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Using square bracket notation
>>> phrase = "Hello world!"
>>> phrase[0]
'H'
>>> phrase[1] The first character
'e' is at index 0.
>>> phrase[2]
Negative index
'l'
>>> phrase[6] values reference
'w’ the end of the list
>>> phrase[-1]
'!'
>>> phrase[-2]
'd'

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


The function len() gives you the
number of elements
Not the last index position.

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


How could this be?

1)An error because string can’t be


redefined.

2)string is “1.0000000000/3”

3)string is “0.333333333333”

4)string is ©“1/3.0000000000”
2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Use the range() function to
generate index values
>>> print range(0,5)
>>> for index in
[0, 1, 2, 3, 4]
range(0,3):
>>> print range(0,3)
... print index
[0, 1, 2]
...
>>> print range(3,0)
0
[]
1
>>> print range(0,5,2)
2
[0, 2, 4]
>>> print range(0,7,3)
[0, 3, 6]
>>> print range(5)
[0, 1, 2, 3, 4]
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Print the string, by index
def parts2(string):
for index in
range(len(string)):
print string[index]

>>> parts2("bear")
b
e
a
r

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


Mirroring, by index
def mirrorHalfString(string):
pile=""
for index in range(0,len(string)/2):
pile = pile+string[index]
for index in range(len(string)/2,0,-1):
pile = pile+string[index]
print pile
>>> mirrorHalfString("elephant")
elephpel
>>> mirrorHalfString("something")
sometemo © 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Reversing, by index
def reverseString2(string):
pile=""
for index in range(len(string)-1,-1,-1):
pile = pile+string[index]
print pile

>>> reverseString2("happy holidays")


syadiloh yppah

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


Separating, by index
def separate(string): >>> separate("rubber
baby buggy bumpers")
odds = "" Odds: ubrbb ug upr
evens = "" Evens: rbe aybgybmes
for index in range(len(string)):
if index \% 2 == 0:
evens = evens + string[index]
if not (index \% 2 == 0):
odds = odds +string[index]
print "Odds: ",odds
print "Evens: ",evens
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
If I want to print the “e”
which should I use?

1)print word[4]

2)print word[3]

3)print word[5]

4)print word[e]
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
If I want to print the “g”
which should I use?

1)print word[-1]

2)print word[‘g’]

3)print word[9]

4)print word[8]
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
If I want to print “thing”
which should I use?

1)print word[4:9]

2)print word[5:9]

3)print word[4:10]

4)print word[4:8]

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


Getting an index for a string
>>> print "abcd".find("b")
1
>>> print "abcd".find("d")
3
>>> print "abcd".find("e")
-1

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


Creating a cipher alphabet
def buildCipher(key):
alpha="abcdefghijklmnopqrstuvwxyz"
rest = ""
for letter in alpha:
if not(letter in key):
rest = rest + letter>>> buildCipher("earth")
print key+rest earthbcdfgijklmnopqsuvwxy
z

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


Encoding with keyword cipher
def encode(string,keyletters):
alpha="abcdefghijklmnopqrstuvwxyz"
secret = ""
for letter in string:
index = alpha.find(letter)
secret = secret+keyletters[index]
print secret
>>> encode("this is a
test","earthbcdfgijklmnopqsuvwxyz")
sdfqzfqzezshqs

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


Decoding with keyword cipher
def decode(secret,keyletters):
alpha="abcdefghijklmnopqrstuvwxyz"
clear = ""
for letter in secret:
Why z?
index = keyletters.find(letter) Think
clear = clear+alpha[index] about
print clear spaces
>>> decode("sdfqzfqzezshqs",
"earthbcdfgijklmnopqsuvwxyz")
thisziszaztest

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


Splitting strings into words
>>> "this is a >>> sentence = "Dog bites
man"
test".split()
>>> parts = sentence.split()
['this', 'is', 'a', 'test'] >>> print len(parts)
>>> "abc".split() 3
>>> print parts[0]
['abc']
Dog
>>> "dog bites >>> print parts[1]
man".split() bites
['dog', 'bites', 'man'] >>> print parts[2]
man

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


Koan generator
def koan(sentence):
parts = sentence.lower().split()
subject = parts[0]
verb = parts[1]
object = parts[2]
print "Sometimes "+sentence
print "But sometimes "+object+" "+verb+"
"+subject
print "Sometimes there is no "+subject
print "Sometimes there is no "+verb
print "Watch out for the stick!"
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Making a koan
>>> koan("dog bites man")
Sometimes dog bites man
But sometimes man bites dog
Sometimes there is no dog
Sometimes there is no bites
Watch out for the stick!

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


Doesn’t know about articles
>>> koan("The woman bites the
apple")
Sometimes The woman bites the apple
But sometimes bites woman the
Sometimes there is no the
Sometimes there is no woman
Watch out for the stick!

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


Is this word here?
>>> if "apple" in ["mother's", "apple", "pie"]:
... print "Sure!"
...
Sure!
>>> if "banana" in ["mother's", "apple", "pie"]:
... print "Sure!"
...
>>>

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


Koan generator with articles
def koan2(sentence): verb = parts[verbindex]
parts = object = parts[objindex]
sentence.lower().split() if object in ["the","a","an"]:
verbindex = 1 object = parts[4]
objindex = 2 print "Sometimes "+sentence
subject = parts[0] print "But sometimes "+object+"
if subject in "+verb+" "+subject
["the","a","an"]: print "Sometimes there is no "+subject
subject = parts[1] print "Sometimes there is no "+verb
verbindex = 2 print "Watch out for the stick!"
objindex = 3

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


Better!
>>> koan2("The woman bites the
apple")
Sometimes The woman bites the
apple
But sometimes apple bites woman
Sometimes there is no woman
Sometimes there is no bites
Watch out for the stick!

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


Encodings for strings
Strings are just arrays of characters
In most cases, characters are just single bytes.
The ASCII encoding standard maps between single
byte values and the corresponding characters
More recently, characters are two bytes.
Unicode uses two bytes per characters so that
there are encodings for glyphs (characters) of
other languages
Java uses Unicode. The version of Python we are
using is based in Java, so our strings are actually
using Unicode.
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Special invisible characters
Backslash escapes
\t is the tab character
\b is backspace
\n is newline
\r is return
\uXXXX is a Unicode character where XXXX is
a hexadecimal number (digits 0-9 plus
characters A-F).

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


What does this function print?
def clone2(astring):
newstring = ""
for i in range(0,len(astring)):
newstring = newstring+astring[i]
print newstring
(1) “newstring”

(2) It will print whatever was input (in astring)

(3) It will print whatever was input backwards

(4) It will generate an error

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


That’s it!

There are ONLY six things


Knowing how
to tell the
computer to
computers can do do these six
things is all
1. They can store data with a name(s). there is to
2. programming
They can name parts of programs (instructions),
a computer.
and follow those instruction when commanded.
3. They can take data apart.
4. They can transform data into other forms.
5. They can follow a set of instructions repeatedly.
6. They can test data (is this true or not?), then
take actions depending on what the result is.

© 2016 Pearson Education, Inc., You have now seen them


Hoboken, NJ. All rights reserved.

You might also like