String objects (str
) are collections of characters (char)
This is different from an int
object. How so? The follow code results in “S” being printed
name = "Smith"
print(name[0])
This code results in an error
number = 12345
print(number[0])
The characters that make up a str
object are sequentially ordered left to right with indices 0, 1, 2, …
Python has no char data type or object as other languages may have. In Python, a char is a string of length 1.
Another example of a collection data type is a list object
We have already seen that string can be added using the +
operator : “first” + " second" = “first second”
The *
operation is defined as well : “ab c” * 2 = “ab cab c”
Order of operations:
“ab c” + “stuff” * 2 = ?
(“ab c” + “stuff”) * 2 = ?
city = “Decorah”
city[0] = “D”
city[1] = “e”
city[-1] = city[6] = “h”
city[-2] = city[5] = “a”
city[-7] = city[0] = “D”
The following code results in “D” being printed. The result of successfully using the string index operator is a str
object.
f_char = city[0]
print(f_char)
A method on any Python object is invoked using object_name.method_name()
Some methods take no parameters, others my accept or require a parameter or parameters.
Please refer to the text for a list of various string methods.
String format()
method example:
person = 'Bob'
time = 'morning'
print('Hello {}, it is good to see you this {}'.format(person, time))
Activity 1: Copy and paste the code above into the first active code window for chapter 9.
The length function - len
. Running the code shown below results in the int
object “7” being printed.
char_n = len("Decorah")
print(char_n)
The slice operator str_object[m:n]
returns the part of the string from the mth character to the nth character, including the first but excluding the last.
Activity 2: Use the second active code window to check your understanding of the slice operator by answering and checking the result for the lines of code shown below.
city = 'Decorah'
print(city[2:5])
print(city[:2])
print(city[2:7])
print(city[2:10])
The strip()
and split()
methods and more string formatting
str_object.strip()
removes the leading and trailing white space as well as the \n
line feed characters
str_object.split('s')
returns a list
of sub-strings split on the string ‘s’
Activity 3: String Formating and Slicing. Copy and paste the following code into the third active code window for Chapter 9 Lab Exercises. Strip it, split it and print it following the format shown below.
line_in = "10056 01012017 c Amazon 33.85 \n"
print("On {} your account had a charge of ${} at {}".format(date, amount, retailer))
PyCharm Activity: String Formating and Slicing. Use PyCharm and a credit card data file made from the data shown below and write a program the reads the data, and prints output, in a formatted style to, a file for a prescribed account number. Name the output file “Trans_acct#.txt” Use the string format()
method, as shown below, to print a line for each transaction.
f_out.write("On {}/{}/{} your account had a charge of ${} at {}".format(month, day, year, amount, retailer))
Credit Card Data
10056 01012017 c Walmart 22.71
10056 01062017 c Fairway 22.24
10056 01112017 c T_Bocks 27.71
10056 01122017 c Koreana 22.63
10289 01032017 c Koreana 14.34
10289 01092017 c Roscoes 50.53
10289 01192017 c Amazon 40.03
10289 01202017 c Walmart 187.13
10289 01222017 c T_Bocks 14.52
10289 01222017 c Pulpit_Rock 28.58
10289 01292017 c Fairway 75.30
19542 01082017 c Pulpit_Rock 21.26
19542 01092017 c Walmart 157.77
19542 01172017 c Amazon 40.10
19542 01192017 c Koreana 31.24
19542 01212017 c Pulpit_Rock 27.71
19542 01302017 c Roscoes 65.82
19542 01302017 c Toppling_Goliath 53.68
10998 01012017 c Fairway 104.21
10998 01032017 c Toppling_Goliath 35.23
10998 01042017 c Oneota_Market 7.28
10998 01042017 c Pulpit_Rock 17.18
10998 01072017 c T_Bocks 43.95
10998 01072017 c Koreana 49.49
10998 01082017 c Pulpit_Rock 51.41
10998 01112017 c Walmart 72.98
10998 01182017 c Koreana 17.43
10998 01202017 c Amazon 7.74
10998 01262017 c Pulpit_Rock 34.47
10998 01292017 c Walmart 15.38
10998 01292017 c Toppling_Goliath 35.66
String Comparison operators ==
, !=
, <, and
>```
cat < catwoman # is True
Catwoman < cat # is True
Cat == cat # is False
Ordering of string characters is done using the assigned ordinal values for each character
ord("char") # returns the ordinal value associated with the input parameter that is a single character in quotes
chr(integer) # returns the character assigned to the input parameter that is an integer
The following is NOT possible:
city = "Decorah"
city[0] = "L"
To accomplish this task, one can do (a new string must be created)
city = "Decorah"
new_city = "L" + city[1:]
The for
loop may to used to traverse the length of a string
city = "Des Moines"
for char in city:
print(char)
Another option is to create an index:
city = "Des Moines"
for i in range(len(city)):
print(city[i])
Another option is a while
loop:
city = "Des Moines"
i = 0
while i < len(city):
print(city[i])
i += 1
in
and not in
OperatorsBoolean result. Is one string a sub-string of another (True
or False
)
Each of the following examples results in True
being printed:
city = "Des Moines"
print('De' in city)
print(' M' in city)
print('' in city)
print('Des Moines' in city)
print('m' not in city)
print('se' not in city)
The last two are particularly import to note.
an empty string is a sub-string of any string
any string is a sub-string of itself
Coding problem in Assignment 18
begin with an empty string “” and accumulate the characters from the original string in reverse order
traversing a string in reverse
Activity 4: Use active code window four for Lab Exercises for Chapter 9. Write a function the takes a str
object of an arbitrary length and returns a str
object with the original first and last characters removed.
Activity 5: Use active code window five for Lab Exercises for Chapter 9. Write a function the takes a list
of str
objects, each a single character, and returns a str
object constructed by ‘glueing’ all the list
items together provided the list
item is not ‘a’, ‘m’, or ‘t’. Next, modify the code so that the function receives a second parameter that is a str
object of letters not to be included.
L-Systems (Lindenmayer system) were designed to model the growth of biological objects
Here is the Wikipedia link
They can be used to create and draw fractal images
An L_system is composed of:
an alphabet = a set of symbols that are either variables that can be replaced and constants that are not replaced
a starting string, called an axiom, made from elements of the alphabet
a set of production rules that define the way variables can be replaced with combinations of variables and constants.
A production consists of two parts: the predecessor and the successor: predecessor \(\rightarrow\) successor
PyCharm Activity: Create a PyCharm project called L-Systems. Create a Python file (name it as you want), and CAP the following code corresponding to the L-system for a binary tree. The alphabet is { 0, 1, [, ] }, with ‘0’ and ‘1’ variables.
import turtle
def apply_rules(ch):
newstr = ""
if ch == '1':
newstr = '11' # Rule 1
elif ch == '0':
newstr = '1[0]0' # Rule 2
else:
newstr = ch # ch is a constant
return newstr
def process_string(old_str):
newstr = ""
for ch in old_str:
newstr = newstr + apply_rules(ch)
return newstr
def create_L_system(num_iters, axiom):
start_string = axiom
end_string = ""
for i in range(num_iters):
end_string = process_string(start_string)
start_string = end_string
return end_string
#def draw_L_system(t, inst, ang, length):
def main():
inst = create_L_system(1, "0")
scale_factor = 1.0
angle = 45
# print(inst)
t = turtle.Turtle()
wn = turtle.Screen()
t.hideturtle()
t.up()
t.goto(0, -250)
t.left(90)
t.down()
t.speed(1)
draw_L_system(t, inst, angle, scale_factor*20)
wn.exitonclick()
main()
Fill in the function draw_L_system
using the following turtle plotting directives:
0: draw a line segment of one-quarter length
1: draw a line segment of full length
[: push position and angle, turn left ang
degrees
]: pop position and angle, turn right ang
degrees
The push and pop directives refer to a LIFO (Last-In-First-Off) stack or list.
When the turtle interpretation encounters a ‘[’, the current position and angle are saved (pushed) onto a stack (a Python list in this case). This is accomplished by list_name.append([t.position(), t.heading()])
The position and heading values are popped (removed) from end of the stack (list) and the turtle location and heading restored when the interpretation encounters a ‘]’. The Pythonic way to accomplish this is pos, dir = list_name.pop()
PyCharm Activity: Modify the binary tree program to draw a fractal plant. The information for doing so is given below:
variables : X, F
constants : +, −, [, ]
axiom : X
rules : X → F[−X][X]F[−X]+FX and F → FF
angle : 25°
Here, F means “draw forward”, − means “turn left 25°”, and + means “turn right 25°”. X does not correspond to any drawing action and is used to control the evolution of the curve. The square bracket “[" corresponds to saving the current values for position and angle, which are restored when the corresponding “]” is executed.
Some others to try …
axiom = F; rule : F \(\rightarrow\) FF-[-F+F+F]+[+F-F-F]; iterations = 4; angle = 22.5\(^o\)
axiom = X; rules : X \(\rightarrow\) F[+X][-X]FX, F \(\rightarrow\) FF; iterations = 7, angle = 25.7\(^o\)
Here is a link to more examples
PyCharm Activity: Choose a plant created and drawn using the L-system method and add randomization to the drawing of the plant. For example, randomize the angle at which a branch is drawn, or the length that a branch is drawn. Additionally, add color to your plant in either a systematic or random way.
Sec. 9.16 Looping and Counting
Sec. 9.17 A find
function
Sec. 9.18 Optional Parameters
def find4(astring, achar, start=0, end=None):
Activity 6: Write a function that takes a potential password as a str
object and determines if it satisfies the requirements for a strong password. The requirements are shown below. The function will alert the user which, if any, of the requirements the proposed password fails to satisfy. Otherwise, it response with the message ‘Successful Choice for a Password!’
it must be at least eight characters in length
it must begin with a letter
it must have at least one uppercase letter
it must have at least one lowercase letter
it must have at least one number
it must have at least one of the following characters: &, #, !, <
it must not include any of the following characters: $, %, @, *
Sec. 9.19 Character Classification