You are on page 1of 93

EECS 1015

Introduction to Computer Science and Programming

Topic 3
Strings and Formatted Output

Fall 2021
Michael S. Brown
EECS Department
York University

EECS1015 – York University -- Prof. Michael S. Brown 1


What is so special about strings?
• Think about how we use computing today . . .
"ok!"

• The vast majority of our computing experience "wth brah"


"lol"
involves communication with other machines over
the internet. "ifyp"
"sup dog" "brb"

• To communicate, we must send data in some format. "j/k"


"eecs1015 rules"

• String data (i.e., a sequences of characters) is one of


the most common formats we use to encode and
transmit data.

EECS1015 – York University -- Prof. Michael S. Brown 2


Text-based information
• When we say "text", we mean characters -- and that means strings.
• Most companies you have heard of -- Facebook, Google, Microsoft,
InfoSys, Tencent, Telegram -- manage huge amounts of text-based
data (customer names, accounts, employee info, products, content,
etc.)

EECS1015 – York University -- Prof. Michael S. Brown 3


Goals of this Lecture
• To learn more about string manipulation and processing in Python

• Introduce you to string indexing and slicing

• Introduce you to objects and methods

• Learn how to do more complex print statements using formatted


output

• To continue to think like that interpreter

EECS1015 – York University -- Prof. Michael S. Brown 4


Part 1: More on string literals
and escape characters

EECS1015 – York University -- Prof. Michael S. Brown 5


String literals – double and single quotes
Simple strings with " and '
You already know double quotes
name = "Yu-Wing Tai"
title = 'CEO' But you can also use single quotes
address = """200 Clearwater Bay
Hong Kong
P.R.C.
Multi-line strings with
"""
favQuote = '''Whatever you do may seem insignificant to you,
What if your string spanned
but it is most important that you do it. multiple lines? We surround
- Mahatma Gandhi these by three double or
''' triple quotes """…"""
print(name) ''' …. '''
print(title)
print(address)
print(favQuote)

https://trinket.io/python/be91155273
EECS1015 – York University -- Prof. Michael S. Brown 6
Multi-line strings
quote1 = """EECS
1015""" When you type provide multi-string literals,
all characters between the """ … """ are part of
quote2 ="""EECS the string.
1015"""
There are spaces here. So if you introduce spaces or tabs, these will
print(quote1) These are part of the string. be part of the string. See below.
print(quote2)

EECS
1015
EECS The spaces from variable quote2 printed out here.
1015 This may not be what you want.

https://trinket.io/python/2f8f57e52b

EECS1015 – York University -- Prof. Michael S. Brown 7


The "new line" character (\n)
days = """Monday When you type in a multi-line string, you have to press the "enter" key
Tuesday on your keyboard to go to the next line.
Wednesday
Thursday When you press "enter", it generated a character.
Friday""" This character is known as the "newline" character.
print(days) A newline char causes the printout to start a new line.

You can imagine there are invisible characters at the end of the line
days = """Monday\n that specify to start a new line. They new line characters
Tuesday\n are drawn here as: \n
Wednesday\n
Thursday\n Actually, the \n is how you can specify a newline character in a string literal .
Friday""" The string here means "Monday(new line)Tuesday(new line) . . . "
print(days) This two character sequence "\n" is known as an escape sequence.

day2 = "Monday\nTuesday\nWednesday\nThursday\nFriday"
print(day2)

EECS1015 – York University -- Prof. Michael S. Brown 8


Escape sequence characters
• In Python, the \ character is a treated specially. It is know as an
"escape" character. It is used to help specify characters that are not
easy to type from the keyboard.
• Common escape sequences:
Escape sequence Meaning/interpretation
\' Single quote
\" Double quote
\n Newline (or line feed)
\t A tab
\\ A slash character

Why the term "escape"? Because the \ character forces the Python interpreter to escape from its normal
interpretation of the string.
EECS1015 – York University -- Prof. Michael S. Brown 9
Think like an interpreter and string
Imagine you wanted the following string: The sign said "No Food".

In this case, you want the quotation mark characters (") to also appear in the string, but we use
quotes to specify the string.

quote = " The sign said "No Food". "


print(quote)

Think the Python interpreter: The interpreter would have trouble


understanding what you intend.
quote = " The sign said "No Food". "
Is this one string with quotes in it,
quote = " The sign said "No Food". " or two strings?

But cause of this confusion, we need


a different way to specify quotes in strings!
EECS1015 – York University -- Prof. Michael S. Brown 10
Strings with quote characters
str1 = "String with a \"quoted\" word." When using double quotes to specify
print(str1) the string literal, you need the \" escape
sequence to specify a double quote character

str2 = 'String with a "quoted" word.' When using single quotes to specify
print(str2) the string literal, you don't need the \"
escape sequence to specify the double quote
character

str3 = 'String with a \'quoted\' word.' When using single quotes to specify
print(str3) the string literal, you need the \' escape
sequence to specify a single quote character

str4 = "String with a 'quoted' word." When using double quotes to specify
print(str4) the string literal, you don't need the \' escape
sequence to specify a single quote character

EECS1015 – York University -- Prof. Michael S. Brown 11


Python raw string - r"strings"
• What if we want to print out a string, but not have the escape
character treated as an escape character?! Below will cause
problems. x = "newline is the \n character"
print(x)

• We could use an escape character for slash (which is \\ )


y = "newline is the \\n character"
print(y)

• But there is another way, known as a "raw string". We add an r


before the first quotation mark.
z = r"newline is the \n character"
print(z)

https://trinket.io/python/3bb4253aab
EECS1015 – York University -- Prof. Michael S. Brown 12
Raw strings literals
r"String"
Adding the r before the string makes the Python interpreter treat
the string as a raw string. Raw strings will ignore escape
characters.

x = r"Raw Strings ignore \t\n\\\r escape characters"


print(x)

https://trinket.io/python/607dcc27d8

EECS1015 – York University -- Prof. Michael S. Brown 13


Part 2: Converting numbers to strings
and formatting strings

EECS1015 – York University -- Prof. Michael S. Brown 14


Last Lecture – string to number
• Last lecture, we discussed that the input() function always
returned a string.
• As a result, we had to convert the string to a number using either
int() or float() Converting a string to a float using the float() function.

number_str = input("Input a price: ")


itemPrice = float(number_str)
discountAmount = 0.2
newPrice = (1.0-discountAmount) * itemPrice
print("Discount Price")
print(newPrice)

EECS1015 – York University -- Prof. Michael S. Brown 15


How about number to string?
• If we want to convert a number (float or integer) to a string, we can
use the str() function:
str(100) returns "100"
str(44.4) returns "44.4"

number_str = input("Input a price: ")


itemPrice = float(number_str)
discountAmount = 0.2 Converting a float to a string using the str() function.

newPrice = (1.0-discountAmount) * itemPrice


percentPaid= (1.0 - discountAmount) * 100
print("You only pay " + str(percentPaid) + " %!")
print("Discount price is $" + str(newPrice))

https://trinket.io/python/932deaa402
EECS1015 – York University -- Prof. Michael S. Brown 16
Think like the interpreter
... Recall from last lecture:
percentPaid= (1.0 - discountAmount) * 100 "string" + number
print("You only pay " + str(percentPaid) + " %!") - causes a run-time error.
... - but here don't want the + to be a math
operator, we want it to be string concat.
So we convert the number to a stirng.
Think like the Python interpreter for this statement.
print("You only pay " + str(percentPaid) + " %!")
print("You only pay " + str(percentPaid) + " %!") step 1: Handle expression
print("You only pay " + str(percentPaid) + " %!") step 2: Start with str()
print("You only pay " + str( 80.0 ) + " %!") step 3: Replace variable with value
print("You only pay " + "80.0" + " %!") step 4: Call function str()
print("You only pay " + "80.0" + " %!") step 5: Concat these two strings
print( "You only pay 80.0" + " %!") step 6: Contact these two strings
print( "You only pay 80.0 %!" ) step 7: call print() with final string

EECS1015 – York University -- Prof. Michael S. Brown 17


String formatting with str()
• str() is useful, but it can be tedious and inefficient
• Consider the following While this works, it is hard to read. Also, the interpreter
name = "Abdel Zhang" has to perform two str() functions and 5 concatenations.
age = 19
height = 182.4 There must be a better way!
weight = 77.8
(This is not related to strings)
print("Hello " + name + "! Age: " + str(age) + \ What is the \ here?
" H: " + str(height) + "cm W: " + str(weight) + "kg") This is a way to split a python
statement that is too long.
Hello Abdel Zhang! Age: 19 H: 182.4cm W: 77.8kg It is known as a "continuation"
character and lets Python know
the statement continues on the next
line. Don't confuse this with an
escape sequence.

https://trinket.io/python/f1c36cbc03
EECS1015 – York University -- Prof. Michael S. Brown 18
Three approaches to string formatting
• #1 String formatting using %

• #2 String formatting using the name holders and the format() method
• Unnamed
• Named
• Ordered

• #3 f-Strings (format strings)

EECS1015 – York University -- Prof. Michael S. Brown 19


String formatting – approach 1 (% operator)
• The % operator is a way to format strings as follows.
print("Hello %s! Age: %d H: %.2f W: %.2f" % (name, age, height, weight))

These indicate where to place variable data


and the type of data the variable is. A list of variables in (), separated by commas.

print("Hello %s! Age: %d H: %.2f W: %.2f" % (name, age, height, weight))

% symbol after string

print("Hello %s! Age: %d H: %.2f W: %.2f" % (name, age, height, weight))


Python generates the new string by placing the data from the
variables at the properly location in the string.
EECS1015 – York University -- Prof. Michael S. Brown 20
String formatting with % syntax

"String data % and % . . . . . % " % (data1, data2, .. . dataN)


string with format symbols data to insert into string

%_ Notation
%s – replace with string data
%d – replace with integer data
%f – replace with floating point (default is 6 digits in the decimal place)
%.#f – replace with floating point and only have # numbers have the decimal place show

The format symbols are used to describe the type of data that will be inserted into the string.
%d seems an odd choice for integer data, it comes from older programming languages (e.g., C) and
means "digits".

For floating point data we can specify how many decimal place digits we want to show. See next slide
for an example:

EECS1015 – York University -- Prof. Michael S. Brown 21


String formatting with %
• Previous example, updated with %
• The result is the same, but code is much easier to read
name = "Abdel Zhang"
age = 19
height = 182.4
weight = 77.8

print("Hello %s! Age: %d H: %.2f W: %.2f" % (name, age, height, weight))

Hello Abdel Zhang! Age: 19 H: 182.40cm W: 77.80kg

https://trinket.io/python/277b38a727

EECS1015 – York University -- Prof. Michael S. Brown 22


Formatting with %
You can use % for any string literal . Here x is assigned to string created with the format % operator.
x = "str '%s', int %d, float %f, formatted float %.3f " % ("hello", 10, 3.33333, 3.33333)
print(x)

str 'hello', int 10, float 3.333330, formatted float 3.333

%_ Notation

%s – replace with string data


%d – replace with integer data
%f – replace with floating point (default is 6 digits in the decimal place)
%.#f – replace with floating point and only have # numbers have the decimal place show

EECS1015 – York University -- Prof. Michael S. Brown 23


String formatting with only a single item
• One of the methods we learned for string formatting was using the %
symbol
• If you only have a single item, you do not need the parenthesis
• Example:
x = 100
print("x = %d " % x )

x = 100

EECS1015 – York University -- Prof. Michael S. Brown 24


String formatting – approach #2 – format()
• To understand approach #2, we need to first discuss objects

• Remember, in Lecture 2, we sometimes called integers, floats, and


strings, objects?

• This is because Python treats all data as objects

EECS1015 – York University -- Prof. Michael S. Brown 25


Python String Object
• A string object hold the value of the string
• It also has several associated functions
• These functions are known as methods

• To perform a method on an object, we use the . symbol as follows

x =" HELLO ".lower()

String object String method lower().


This will compute a new string with
all lower case values of the String object.

EECS1015 – York University -- Prof. Michael S. Brown 26


Calling an Object method (1/3)
• Calling (or invoking) the method lower() Methods associated
Think like the interpreter with string objects
Python code
Before we start the program, the interpreter has scanned
x = "HELLO".lower()
the program knows the following:
print(x) lower()
format()
List of variables Data/Objects stored in memory upper()
hello
x "HELLO" (string) replace()
capitalize()

Python also knows that string objects


have associated methods. Above are
a few we will discuss later in this lecture.
Let's focus on lower() here.
EECS1015 – York University -- Prof. Michael S. Brown 27
Calling an Object method (2/3)
• Calling (or invoking) the method lower()
Now the interpreter executes line 1.
Python code
step 1: there is a method call, it needs to be evaluated x = "HELLO".lower()
x = "HELLO".lower() step 2: perform lower() using object's data x = "HELLO".lower()
print(x) - lower() creates a new string object by converting the
the calling object's values ("HELLO") to lowercase
- this new string object is stored in memory
hello
step 3: bind variable x to this new string object "hello" x = "hello"

List of variables Data/Objects stored in memory


x "HELLO" (string)
"hello" (string)

EECS1015 – York University -- Prof. Michael S. Brown 28


Calling an Object method (3/3)
• Calling (or invoking) the method lower()
Now the interpreter executes line 2. A simple print with the value in x.
Python code
x = "HELLO".method() List of variables Data/Objects stored in memory
print(x) x "HELLO" (string)
"hello" (string)
hello

It is important to note that the lower() methods created a new string


object. It did not change the values in the original object ("HELLO").

EECS1015 – York University -- Prof. Michael S. Brown 29


String format() method
Previous approach: String formatting using %
x = "str '%s', int %d, float %f, formatted float %.3f " % ("hello", 10, 3.33333, 3.33333)
print(x)

str 'hello', int 10, float 3.333330, formatted float 3.333

New approach: String formatting using the .format() method

x = "str {}, int {} float {}, formatted float {:.2f} ".format("hello", 10, 3.33333, 3.33333)
print(x)

https://trinket.io/python/1deb5f8349

EECS1015 – York University -- Prof. Michael S. Brown 30


String formatting with .format() syntax

"String data {} and {} . . . . {:X} ".format(data1, data2,…dataN)


string with {} placeholders and option symbols data to insert into string using format() method

Symbols for datatypes with the format() method

:d – replace with integer data


:f – replace with floating point (default is 6 digits in the decimal place)
:.#f – replace with floating point and only have # numbers have the decimal place show

EECS1015 – York University -- Prof. Michael S. Brown 31


String format() method
• When specifying the string, use {} to put in place holders
• Data will then be placed into these place holder positions
name = "Abdel Zhang"
age = 19
height = 182.4
weight = 77.8

print("Hello {}! Age: {:d} H: {:.2f} W: {:.2f}".format(name, age, height, weight))

You can also specify the datatype you want in the placeholders. https://trinket.io/python/69b9c5777a
If you leave it blank {}, then Python will default to the data provided in
the format method.

EECS1015 – York University -- Prof. Michael S. Brown 32


String format() method
You can also specify the datatype you want in the placeholders.
If you leave it blank {}, then Python will default to the data provided in the format method.
To specify, use a : and then data type symbol.
name = "Abdel Zhang"
age = 19
height = 182.4
weight = 77.8

print("Hello {}! Age: {:d} H: {:.2f} W: {:.2f}".format(name, age, height, weight))

Symbols for datatypes with the format() method

:d – replace with integer data


:f – replace with floating point (default is 6 digits in the decimal place)
:.#f – replace with floating point and only have # numbers have the decimal place show

EECS1015 – York University -- Prof. Michael S. Brown


https://trinket.io/python/69b9c5777a 33
String format() method
• Place holders {} and formatting
• The placeholder are intended to be used with format()
• E.x.: x = "Hello {}! You are {} today!" New strings created by format()
y = x.format("EECS1015", 1) "Hello EECS1015! You are 1 today!"
z = x.format("D. Graham", 33) "Hello D. Graham! You are 33 today!"

name1 = "Abdel Zhang"


age1 = 18
name2 = "Calum MacLeod"
age2 = 47
x = "Hello {}! You are {} today!"
print(x)
print(x.format(name1, age1))
print(x.format(name2, age2))
https://trinket.io/python/8c2cd17d8f
EECS1015 – York University -- Prof. Michael S. Brown 34
Calling format() method (1/4)
• Calling (or invoking) the method format() Methods associated
Think like the interpreter with string objects
Python code
Before we start the program, the interpreter has scanned
x = "Name: {} Age: {}" the program knows the following:
y = x.format("EECS1015", 1) lower()
z = x.format("Drake", 34) format()
List of variables Data/Objects stored in memory upper()
x "Name: {} Age: {}" (string) replace()
y capitalize()
z …

First, we perform line 1, that binds x to the string object.


x = "Name: {} Age: {}"
y = x.format("EECS1015", 1) List of variables Data/Objects stored in memory
z = x.format("Drake", 34) x "Name: {} Age: {}" (string)
y
z
EECS1015 – York University -- Prof. Michael S. Brown 35
Calling format() method (2/4)
• Calling (or invoking) the method format()
x = "Name: {} Age: {}" Think like the interpreter
y = x.format("EECS1015", 1) Now we perform line 2.
z = x.format("Drake", 33) Step 1: evaluate method y = x.format("EECS1015", 1)
Step 2: Use string x is y = "Name: {} Age: {}".format("EECS1015", 1)
bound to.
Step 3: call method y = "Name: {} Age: {} ".format("EECS1015", 1)
format(). It creates a new
string.
y = "Name: EECS1015 Age: 1"
Step 4: bind y to this
new string object y = "Name: EECS1015 Age: 1"

List of variables Data/Objects stored in memory


x "Name: {} Age: {}" (string)
y "Name: EECS1015 Age: 1" (string)
z
EECS1015 – York University -- Prof. Michael S. Brown 36
Calling format() method (3/4)
• Calling (or invoking) the method format()
x = "Name: {} Age: {}" Think like the interpreter
y = x.format("EECS1015", 1) Now we perform line 3.
z = x.format("Drake", 34) Step 1: evaluate method z = x.format("Drake", 33)
Step 2: Use string x is z = "Name: {} Age: {}".format("Drake", 34)
bound to.
Step 3: call method z = "Name: {} Age: {} ".format("Drake", 34)
format(). It creates a new
string.
z = "Name: Drake Age: 34"
Step 4: bind z to this
new string object z = "Name: Drake Age: 34"

List of variables Data/Objects stored in memory


x "Name: {} Age: {}" (string)
y "Name: EECS1015 Age: 1" (string)
z "Name: Drake Age: 34" (string)
EECS1015 – York University -- Prof. Michael S. Brown 37
Calling format() method (4/4)
• Calling (or invoking) the method format()
x = "Name: {} Age: {}" List of variables Data/Objects stored in memory
y = x.format("EECS1015", 1)
z = x.format("Drake", 34) x "Name: {} Age: {}" (string)
y "Name: EECS1015 Age: 1" (string)
z "Name: Drake Age: 34" (string)

Note: When this program is done, the initial string "Name: {} Age: {}" is never changed.
Each time the method format() is called, it creates a new string object.

We can apply the method format() multiple times to the same string with different
parameters passed to the format() method.

EECS1015 – York University -- Prof. Michael S. Brown 38


Format() with Named Placeholders
• Named placeholders

We provide names for the placeholders.


x = " Hello {name} – You are {age} years old"
When we call the format() method, we have
y = x.format( name="Drake" , age="34" )
to also provide the name in the call.
z = x.format( age=34 , name="Drake" )
print(y)
Notice order the named placeholders are
print(z)
provide in format() doesn't matter.

https://trinket.io/python/9244ac6599

EECS1015 – York University -- Prof. Michael S. Brown 39


Format() with Ordered Placeholders
• Ordered placeholders- The place holder has a number which
refers to the order in which the parameters
are specified in the format() call.
format(0, 1, 2, 3, 4)
x = "Hello {0} – You are {1} years old"
y = x.format( "Drake", 34) For example:
z = x.format( 1, "EECS1015" ) format("Drake", 34) - "Drake" is order 0, 34 is order 1
print(y) format(1, "EECS1015") – 1 is order 0,
print(z) "EECS1015" is order 1
print("Hello {1} – You are {0} years old".format(25, "Sam"))

Notice, our placeholders can access in different order.

https://trinket.io/python/f7a8ebbb77

EECS1015 – York University -- Prof. Michael S. Brown 40


Specifying formatting for floats
We can also specify some formatting options in the .format method.
We will only discuss formatting floating values.
Float data defaults to printing with 6
digits after the decimal place. This can
item = "Bread"
price = 1.99 look bad.
x = "Item: {} Price: ${:.2f}" For example: Price $1.990000
y = "Item: {0} Price: ${1:.2f}"
z = "Item: {item} Price: ${price:.2f}" To fix this we can specify how we want
print(x.format(item, price)) to format the float (similar to how we did it
print(y.format(item, price)) with the % method).
print(z.format(item=item, price=price))
For the {} methods, we have to put in a :.Xf,
https://trinket.io/python/0bbd0f4c2a where X is the number of digits after the
decimal we want to see.

For named and ordered placeholders,


the colon comes immediately after the name
or order data.
EECS1015 – York University -- Prof. Michael S. Brown 41
Last line of previous example
This expression is a bit interesting, so let's discuss it. z.format(item=item, price=price)

item = "Bread" When the expression is evaluate, we already have the following:
price = 1.99 List of variables Data/Objects stored in memory
..
z = "Item: {item} Price: ${price:.2f}" z "Item: {item} Price: ${price:.2f}"
.. item "Bread" (string)
print(z.format(item=item, price=price)) price 1.99 (float)

Think like an interpreter to evaluate the expression:


(1) z.format(item= item, price=price)
step 1: replace item with bound value – this is for the left item
step 2: replace price with bound value – this is for the left item (2) z.format(item="Bread", price=price)
step 3: access string object bound to z (3) z.format(item=item, price=1.99)
step 4: call format method (4) "Item: {item} Price: ${price:.2f}". format(item="Bread", price=1.99)
the right item and price are used "Item: {item} Price: ${price:.2f}".format(item="Bread", price=1.99)
by the format method.
step 5: string result from format method (5) "Item: Bread Price: $1.99"

This is confusing because the named parameters item and price are the same as the variables
item and price. But Python will treat these differently based on the syntax. We will see this
again when we learn about Python functions.
EECS1015 – York University -- Prof. Michael S. Brown 42
String formatting – approach #3 – f-strings
• The last example on the previous slide brings us to an interesting
point
• Often as the programmer, we know the name of the variables we
want to insert into our string
• Methods 1 and 2 essentially make us "pass" this data as shown
below:
item = "Bread"
price = 1.99
x = "Item: %s Price: %.2f" % (item, price)

y = "Item: {item} Price: ${ price:.2f }".format( item=item, price=price)

print(x)
print(y)

EECS1015 – York University -- Prof. Michael S. Brown 43


New Python feature – f-string syntax
f" Sting data {variable_name} more string data {variable_name:format_info}"

add a f before the quote first " bracket notation directly it is also possible to put in
refers to a variable in the code formatting information

item = "Bread"
price = 1.99
x = "Item: %s Price: %.2f" % (item, price)
y = "Item: {item} Price: ${price:.2f}".format( item=item, price=price)
z = f"Item: {item} Price: ${price:.2f}"

print(x)
print(y)
print(z)

Unfortunately this is so new it isn't


supported by Trinket.
Cut and past the code directly into
EECS1015 – York University -- Prof. Michael S. Brown PyCharm and run it. 44
Another example of f-string
Python code
name = input("Your name: ")
height = input("Your height in cm: ")

print(f"{name} is {height}cm.") # see how the f-string directly references


# the variables above

Your name: Michael (input by the user)


Your height in cm: 180.9 (input by the user)
Michael is 185.9cm. (formatted output by f-string)

Sorry, f-string is so new it is


not supported by trinket.io yet.

EECS1015 – York University -- Prof. Michael S. Brown 45


Common mistakes w/ format string (1/2)
• When first learning formatting, expect to make mistakes
• Here are some common ones
Forgot to add in spaces between
item = "Bread" text and items to insert into the string.
price = 1.99
x = "Item%s Price%f" % (item, price)
y = "Items %s Price%2.f" % (item, price) Formatting syntax is wrong. This is
z = "Items %s Price %.2f" % (item) a very common mistake.

print("x = " + x)
Forgot to include all the variables
print("y = " + y)
print("z = " + z)
needed by the format string

x = ItemBread Price1.9900000 No space


y = Items Bread Price%2.f
Incorrect syntax for formatting floats
z = Items Bread Price nan
Forgot to include all variables, "nan" stands
https://trinket.io/python/325d581ec7 for not a number.
EECS1015 – York University -- Prof. Michael S. Brown
Common mistakes w/ format string (2/2)
• More mistakes using the {} and format() method Forgot to add in spaces between
text and items to insert into the string.
item = "Bread"
price = 1.99 Formatting syntax is wrong. This is
x = "Item{} Price{:.2f}".format(item, price)
a very common mistake. You may get
y = "Item {} Price {:2f}".format(item, price)
z = "Item {} Price {:.2f}".format(item)
a run-time error if the formatting is too
w = "Item {} Price {:.2f}".format(price,item) iincorrect.
print("x = " + x)
print("y = " + y) Forgot to include all the variables
print("z = " + z) needed by the format string
print("w = " + w)

x = ItemBread Price1.99 Order of variables in format() is


y = Item Bread Price 1.990000 wrong.
z = Item Bread Price nan
w = Item 1.99 Price nan

https://trinket.io/library/trinkets/27d3143433

EECS1015 – York University -- Prof. Michael S. Brown 47


Summary for formatted printing
To recap this section - there are 4 ways to build a string with data
Assume we have variables name = "Su Luan", age=33
(1) concatenate and str() function (not preferred)
"hello " + name + " you are " + str(age) + "today"
(2) % operator (older method – less preferred)
"hello %s you are %d today " % (name, age)
(3) {} and format method (more common – with three (3) variations)
"hello {} you are {} today".format(name, age)
"hello {Name} you are {Age} today".format(Name=name, Age=age)
"hello {0} you are {1} today".format(name, age)
(4) Newest approach f-string (Python 3)
f"hello {name} you are {age} today"

All the above give the same output.


https://trinket.io/python/9bbde1aaf3

EECS1015 – York University -- Prof. Michael S. Brown 48


Part 3: Indexing and slicing strings

EECS1015 – York University -- Prof. Michael S. Brown 49


Recall our initial discussion on strings
a = "Hello World"

0 8 9 10
1 2 3 4 5 6 7 string

characters H e l l o W o r l d

index 0 1 2 3 4 5 6 7 8 9 10

We can think of the characters that make up our string


as having a position (or index) in the string.

EECS1015 – York University -- Prof. Michael S. Brown 50


Index into the string – bracket [] notation
• Python allows us to index into the string using brackets
StringObject[ index ] This expression creates a new string object of a single character at
the index position from the StringObject.
a = "Hello World"
start = a[0]
H e l l o W o r l d
middle = a[5]
end = a[10] 0 1 2 3 4 5 6 7 8 9 10
print(a)
print(start)
print(middle)
a[0] a[5] a[10]
print(end)
print("'{}'-'{}'-'{}'".format(start, middle, end))

Hello World
H

d https://trinket.io/library/trinkets/64085b59ae
'H'-' '-'d'

EECS1015 – York University -- Prof. Michael S. Brown 51


String length - len() function
• Python has a function that returns the length of a string (i.e., the number
of characters in the string)

len("string") returns the size of the string.


remember we start counting from 0.
so last character is length-1

a = "The quick brown fox jumps over the lazy dog"


str_length = len(a)
last_letter = a[str_length-1]
print(a)
print("a's length is %d" % (str_length))
print("last letter is %s" % (last_letter))

https://trinket.io/library/trinkets/98fed47917

EECS1015 – York University -- Prof. Michael S. Brown 52


Negative indexing
• Python also allows you to index using negative numbers
• Negative -1 starts at the last character
• The maximum you can go negative would be negative the length of
the string
a = "Hello World" H e l l o W o r l d
end = a[-1]
print("Last char is " + end) -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

d a[-11] a[-7] a[-3]

EECS1015 – York University -- Prof. Michael S. Brown 53


IndexError out of range error
• If you give an index (negative or positive) that goes outside the
length of the string, you'll get a run-time error
x = "CANADA"
print(x[1])
print(x[6]) "CANADA" is of length 6
But remember, we start indexing from 0, so the last
A character is at index 5.
line 3: This line of code will cause an "out of range" error.
print(x[6])
IndexError: string index out of C A N A D A
range
0 1 2 3 4 5

EECS1015 – York University -- Prof. Michael S. Brown 54


IndexError out of range error
• If you give an index (negative or positive) that goes outside the
length of the string, you'll get a run-time error
x = "CANADA"
print(x[-2])
print(x[-10]) "CANADA" is of length 6, so anything smaller than -6
is out of range.
D This line of code will cause an "out of range" error.
line 3:
print(x[-10]) C A N A D A
IndexError: string index out of -6 -5 -4 -3 -2 -1
range

EECS1015 – York University -- Prof. Michael S. Brown 55


String slicing a[start_index:end_index]
• You can also specify a range of characters using [start:end]
T a v a r i s h V P
0 1 2 3 4 5 6 7 8 9 10

a[0:7] a[9:11]
start index end index start index end index

a = "Tavarish VP"
b = a[0:7] The first index number is where the slice starts
c = a[9:11] (inclusive), and the second index number is where the
print("a[0:7]={} a[9:11]={}".format(a,b))
slice ends (exclusive, i.e., that character is not
included). Yes, it is annoying that the end_index is not
a[0:7]=Tavaris a[9:11]=VP included in the resulting "sliced" string.

https://trinket.io/python/7d64cd98b4
EECS1015 – York University -- Prof. Michael S. Brown 56
Slicing with negative indices
• Slice ranges can also specified in negative numbers
T a v a r i s h V P
positive index 0 1 2 3 4 5 6 7 8 9 10
negative index -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

a[-10:4] a[7:-1]
start index end index start index end index

a = "Tavarish VP"
b = a[-10:4] We can also use negative index for both the
c = a[7:-1] start or stop index.
print("a[-10:4]={} a[7:-1]={}".format(b,c))
Question: Could you use a negative index for the
end index and have the last character in the sliced string?
a[-10:4]=ava a[7:-1]=h v

https://trinket.io/python/a96a3e1050
EECS1015 – York University -- Prof. Michael S. Brown 57
What about slicing out of range?
• Interestingly, when you slice out of range you do not get an index
error. Instead, you will the characters within the range specified. If
no characters are inside your range, Python returns an empty string.
C A N A D A
nothing here!
0 1 2 3 4 5

a[1:10] a[10:20]

a = "CANADA"
b = a[1:10] # result is "ANADA" Out of range indices do not result in
c = a[10:20] # results is "" (empty) an run-time index error. Instead,
print("Results '%s' and '%s' " % (b, c)) if no characters are found in the range,
a null (or empty) string is returned.
Results 'NADA' and ''

EECS1015 – York University -- Prof. Michael S. Brown 58


Variables as indices
• We can also use variables as indices in our code
E E C S 1 0 1 5 Think the like the interpreter
0 1 2 3 4 5 6 7 8

step 1: evaluate express a[start:end] b = a[start:end]


a = "EECS 1025"
start = 0 step 2: replace start with value b = a[ 0 :end]
end = 4
b = a[start:end] step 3: replace end with value b = a[ 0 : 4 ]
print(b)
step 4: access string object bound to a b = "EECS 1015"[ 0 : 4 ]
EECS (I will just write out the string here)
b = "EECS 1015"[ 0 : 4 ]
step 5: perform string slice
- this creates a new string "EECS" (placed in memory)

step 6: bind variable b to this new string b = "EECS"

https://trinket.io/python/7399215923
EECS1015 – York University -- Prof. Michael S. Brown 59
Slicing using variables – Example #2
start = 0
end = 10 Slicing can take
longStr = "This string is 28 chars long" integer variables
shortStr = longStr[start:end] to denote the
print(longStr)
start and end
print(shortStr)
print('Original string = "%s" ' % longStr)
of the slice.
print('Sliced string = "%s" ' % shortStr)

Original string = "This string is 28 cars long"


Sliced string = "This strin"

https://trinket.io/python/9ebc771c9b

EECS1015 – York University -- Prof. Michael S. Brown 60


Variable reassignment with slice
• Consider the following code. A variable bound to a string is
assigned to its own slice result.
a = "Tavarish VP" line 2: a is now bound to new string "Tavarish"
a = a[0:8] The original string "Tavarish VP" is no longer
a = a[-4:-1] bound to any variable.
print(a)

What is the result of this line?

https://trinket.io/python/9909f017a5

EECS1015 – York University -- Prof. Michael S. Brown 61


String indexing and slicing (1/4)
Think like the interpreter
Let's do a simple example to help make sure you understand how the interpreter handles
indexing and slicing.
Before we start the program, the interpreter has scanned
Python code the program knows the following:
x = "CANADA" List of variables Data/Objects stored in memory
a = x[1]
x = x[1:-2] x "CANADA" (string)
print(a) a
print(x)

line 1: bind variable x to string object ("CANADA")


x = "CANADA"
a = x[1] List of variables Data/Objects stored in memory
x = x[1:-2] x "CANADA" (string)
print(a) a
print(x)

EECS1015 – York University -- Prof. Michael S. Brown 62


String indexing and slicing (2/4)
Think like the interpreter
line 2: a = x[1]
x = "CANADA"
a = x[1] step 1: evaluate expression x[1] a = x[1]
x = x[1:-2]
print(a) step 2: access x string object a = "CANADA"[1]
print(x) (I will just draw the string here)
step 3: perform index operation a = "CANADA"[1]
step 4: bind a to new string object "A" a = "A"
index
operation
creates
new string
of a single
List of variables Data/Objects stored in memory character
x "A"
"CANADA" (string)
a "A" (string)

EECS1015 – York University -- Prof. Michael S. Brown 63


String indexing and slicing (3/4)
Think like the interpreter
line 3: x = x[1:-2]
x = "CANADA"
a = x[1] step 1: evaluate expression x[1:-2] x = x[1:-2]
x = x[1:-2]
print(a) step 2: access x string object x = "CANADA"[1:-2]
print(x) (I will just draw the string here)
step 3: perform index operation x = "CANADA"[1:-2]
step 4: bind x to new string object "ANA" x = "ANA"
slicing
operation
creates
new string
List of variables Data/Objects stored in memory "ANA"

x "CANADA" (string)
a "A" (string)
"ANA" (string)

EECS1015 – York University -- Prof. Michael S. Brown 64


String indexing and slicing (4/4)
Think like the interpreter
Python code lines 4 & 5: print out string bound to the variables

x = "CANADA"
List of variables Data/Objects stored in memory
a = x[1]
x = x[1:-2] x "CANADA" (string)
print(a) a "A" (string)
print(x)
"ANA" (string)

This simple code creates two new strings "A" and "ANA". At the end of the
code no variable has access to the initial string literal "CANADA".

EECS1015 – York University -- Prof. Michael S. Brown 65


Slicing with only start or end index
• You can also give only the start or end index.
A B C D E F G H I J
0 1 2 3 4 5 6 7 8 9

a = "ABCDEFGHIJ" strVar[start:]
subStr1 = a[3:] # treated the same as a[3:10] Since no "end" index is given, this
subStr2 = a[:5] # treated the same as a[0:5] notation means slice from specified
print("a[3:]={} a=[:5]={}".format(subStr1, subStr2)) start to the end of the string.

a[3:]=DEFGHIJ a=[:5]=ABCDE strVar[:end]


Since no "start" index is given, this
notation means slice from begging
https://trinket.io/python/314d4ff8a4 of the string up to the specified end.

EECS1015 – York University -- Prof. Michael S. Brown 66


Part 4: More string methods

EECS1015 – York University -- Prof. Michael S. Brown 67


String methods
• We have already seen the format() method
• There are many additional string methods
• Each of these methods will take the form:

"String object".method()

strVariable.method()

EECS1015 – York University -- Prof. Michael S. Brown 68


Methods
Method name Description Data type returned by method
capitalize() Makes first letter in string upper case String
casefold()/lower() Makes a letters in string lowercase String
count() Counts the number occurrences of string Integer
find() Finds the index of the first occurrence of a string Integer
islower() Checks if the string is all lowercase True/False (Boolean)
isupper() Checks is the string is all uppercase True/False (Boolean)
isnumeric() Checks to see if the string represent an integer True/False (Boolean)
replace() Replaces part of the string with a new string String
strip() Removes all leading and ending white spaces String
title() Makes the first letter of each word uppercase String
upper() Converts the whole string to uppercase letters String

EECS1015 – York University -- Prof. Michael S. Brown 69


capitalize() returns a string
txt1 = "This is a test."
txt2 = "THIS IS A TEST." The captialize() method creates a new string
txt3 = "this is a test." where only the first letter of the string is
a = txt1.capitalize() uppercase and the rest of the string is
b = txt2.capitalize()
c = txt3.capitalize()
lowercase.
print("Results:\n{}\n{}\n{} ".format(a,b,c))
See examples, in particular what happens
to variable txt2.
Results:
This is a test.
This is a test.
This is a test

https://trinket.io/python/81517385ca

EECS1015 – York University -- Prof. Michael S. Brown 70


casefold()/lower() returns a string
txt1 = "This is a test."
txt2 = "THIS IS A TEST." lower()/casefold() method creates a new string
txt3 = "this is a test." that convers all the characters in the string
a = txt1.lower() to lower case. If the string is already all lower
b = txt2.lower()
c = txt3.lower()
case, it doesn't do anything (see txt3).
print("Results:\n{}\n{}\n{} ".format(a,b,c))
casefold() is a newer method and not supported
by trinket.io.
Results:
this is a test.
this is a test.
this is a test

https://trinket.io/python/64698c5b03

EECS1015 – York University -- Prof. Michael S. Brown 71


count(x) returns an integer
txt1 = "This is a test."
txt2 = "THIS IS A TEST." The count() method takes a string parameter x.
txt3 = "this is a test." The method counts the number of times
a = txt1.count("T") x appears in the string that the method is
b = txt2.count("T")
c = txt3.count("is")
applied too. The search string x does not have
print("Results:\n{}\n{}\n{} ".format(a,b,c)) to be a character, it can be a string. Sometime
x is called a "substring".

Results:
1
3
2

https://trinket.io/python/7113b683ce

EECS1015 – York University -- Prof. Michael S. Brown 72


find(x) returns an integer
txt1 = "This is a test."
txt2 = "THIS IS A TEST." find(x) returns the index of the first occurance
txt3 = "this is a test." of the string provided in x.
a = txt1.find("test")
b = txt2.find("TH")
c = txt3.find("B")
If the string x is not found, the find() returns
print("Results:\n{}\n{}\n{} ".format(a,b,c)) -1, which means x isn't present in the string.
(see result c on variable txt3)

Results:
10
0
-1

https://trinket.io/library/trinkets/c79a4ba810

EECS1015 – York University -- Prof. Michael S. Brown 73


islower()/isupper()/isnumeric()
returns a Boolean (True/False)
txt1 = "This is a test."
txt2 = "THIS IS A TEST." These methods all return either True/False
txt3 = "2020" if the string is all lower case, all upper case,
a = txt1.islower() # False or represents an integer (numeric).
b = txt2.isupper() # True
c = txt3.isnumeric() # True
d = txt1.isnumeric() # False Note that on trinket.io the results output
print("Results:\n{}\n{}\n{}\n{}".format(a,b,c,d)) as 0 (false) or 1 (true). The results here
are from PyCharm.
Results:
False
True
True
False

https://trinket.io/python/ab5f65b749

EECS1015 – York University -- Prof. Michael S. Brown 74


replace(x,y) returns a string
txt1 = "This is a test." The method replace(x,y) searches for the
txt2 = "THIS IS A TEST."
substring x and replaces with y.
txt3 = "EECS1015 is my least favorite course!"
a = txt1.replace(" ", "*")
b = txt2.replace("T", "X") For example:
c = txt3.replace("least", "most") replace(" ", "_") would find
d = txt2.replace("T", "") # deletes all T
all spaces and replace them with an underscore.
print("Results:\n{}\n{}\n{}\n{}".format(a,b,c,d))

Results: replace(" ", "") would find all spaces and replace
This*is*a*test. it with an empty string. This effectively deletes
XHIS IS A XESX. the spaces in a string.
EECS1015 is my most favorite course!
HIS IS A ES.

https://trinket.io/python/5814cf5022

EECS1015 – York University -- Prof. Michael S. Brown 75


strip() returns a string
txt1 = " Space before."
txt2 = " Spaces before and after. " strip() is used to remove any spaces before
txt3 = "Space after. " or after a string. This is generally applied to
a = txt1.strip() input to avoid when someone types in lots
b = txt2.strip()
c = txt3.strip()
of spaces.
print("Results:\n{}\n{}\n{} ".format(a,b,c))

Results:
Space before.
Spaces before and after.
Space after.

https://trinket.io/python/61ef84f71a

EECS1015 – York University -- Prof. Michael S. Brown 76


title() returns a string
txt1 = "This is a test."
txt2 = "THIS IS A TEST." The title() method creates a new string
txt3 = "this is a test." where the first letter of all words are
a = txt1.title() in uppercase and the rest lower. This
b = txt2.title()
c = txt3.title()
is like the title of a book.
print("Results:\n{}\n{}\n{} ".format(a,b,c))

Results:
This Is A Test.
This Is A Test.
This Is A Test.

https://trinket.io/python/6e9d3ca3e8

EECS1015 – York University -- Prof. Michael S. Brown 77


upper() returns a string
txt1 = "This is a test."
txt2 = "THIS IS A TEST." upper() method creates a new string
txt3 = "this is a test." that convers all the characters in the string
a = txt1.upper() to upper case. If the string is already all upper
b = txt2.upper()
c = txt3.upper()
case, it doesn't do anything (see txt2).
print("Results:\n{}\n{}\n{} ".format(a,b,c))

Results:
THIS IS A TEST.
THIS IS A TEST.
THIS IS A TEST.

https://trinket.io/python/64698c5b03

EECS1015 – York University -- Prof. Michael S. Brown 78


Method after method after method
msg = " Hello World! "
ex1 = msg.strip().upper()
ex2 = msg.strip().upper().replace("LL","XX")
ex3 = msg.strip().lower()[6:11]
print("Results:\n'{}'\n'{}'\n'{}'".format(ex1, ex2, ex3))

Results:
'HELLO WORLD!'
'HEXXO WORLD!'
'world'

Let's examine how the Python interpreter processes this program


on the following slides . . .

EECS1015 – York University -- Prof. Michael S. Brown 79


Method after method after method (1/3)
• Let's consider the this statement:
msg = " Hello World! "
ex1 = msg.strip().upper()

step 1: access string ex1 = msg.strip().upper()


value for msg
ex1 = " Hello World! ".strip().upper()
step 2: apply strip()
method to string – this
results a new string ex1 = "Hello World!".upper()

step 3: apply upper() ex1 = "HELLO WORLD!"


(on the new string) to
get yet another new
string ex1 = "HELLO WORLD!"

step 4: bind ex1 to final string

EECS1015 – York University -- Prof. Michael S. Brown 80


Method after method after method (2/3)
msg = " Hello World! "
Now this statement ex2 = msg.strip().upper().replace("LL","XX")

step 1: access string ex2 = msg.strip().upper()


value for msg
ex2 = " Hello World! ".strip().upper().replace("LL", "XX")
step 2: apply strip()
method to string – this
results a new string ex2 = "Hello World!".upper(). replace("LL", "XX")

step 3: apply upper() ex2 = "HELLO WORLD!". replace("LL", "XX")


(on the new string) to
get yet another new
string ex2 = "HEXXO WORLD!"
step 4: apply replace()
method to get a final ex2 = "HEXXO WORLD!"
new string
step 5: bind ex2 to final string

EECS1015 – York University -- Prof. Michael S. Brown 81


Method after method after method (3/3)
msg = " Hello World! "
Now this statement ex3 = msg.strip().lower()[6:11]

step 1: access string ex3 = msg.strip().lower()[6:11]


value for msg
ex3 = " Hello World! ".strip().lower()[6:11]
step 2: apply strip()
method to string – this
results a new string ex3 = "Hello World!".lower()[6:11]

step 3: apply upper() ex3 = "hello world!"[6:11]


(on the new string) to
get yet another new
string ex3 = "world"
step 4: apply slice[6:11]
to get a final ex3 = "world"
new string
step 5: bind ex2 to final string

EECS1015 – York University -- Prof. Michael S. Brown 82


Comment on methods
• All of these examples result in a new object, either a new string, a
new integer, or a new Boolean (True/False)

• The string object that performed the method is never modified.

• It is also common to combine methods in a single line of code

EECS1015 – York University -- Prof. Michael S. Brown 83


Part 5: Putting it all together

EECS1015 – York University -- Prof. Michael S. Brown 84


Putting it all together – Example 1
• Let's use what we know from Topic 2 and this Topic to do a simple
program
• Task:
Ask user for name.
Ask user for country.
Ask user for height in centimeters.

Output Format: Welcome First Last (CA) - Your height is 74.13 inches.

User's name. Height converted from


No extra spaces, centimeters to inches.
First Last name in uppercase, Code for country,
rest lower case. using first and last letters Formula:
of country entered, all 1cm = 0.393701 inches
upper case.
EECS1015 – York University -- Prof. Michael S. Brown 85
Example code running
--------------------------
Welcome to "Height Converter 2021"
Please input the following information.
Your name:
Your country:
Your height in centimeters
--------------------------
Input from the user is
Your full name: Justin TRUDEAU shown in red.
Your country: canada
Your height: 188.33

Welcome Justin Trudeau (CA) - Your height is 74.15 inches.

EECS1015 – York University -- Prof. Michael S. Brown 86


Python Code https://trinket.io/python/44e197c3e6
welcomeMsg = """
--------------------------
Welcome to \"Height Converter 2021\" Simple multi-line string to print as a welcome
Please input the following information.
Your name: message.
Your country:
Your height in centimeters
--------------------------
"""

# input data
print(welcomeMsg) Print welcome.
name = input("Your full name: ")
country = input("Your country: ")
Input data. Remember this is all string data.
height_cm = input("Your height: ")

# process name
name = name.strip() # remove unwanted spaces Process the name by stripping off any unwanted spaces.
name = name.title() # Name first letter of all words capital Make first letter of each name upper, the rest lower.
# process country
country = country.strip() Process country by stripping of unwanted spaces.
country = country.upper() Convert to uppercase. Extract first and last characters and concat.
countryCode = country[0] + country[-1]

# process height Compute height in inches. Remember to convert user input


height_in = float(height_cm) * 0.393701
to float.
## output
print("Welcome {} ({}) - Your height is {:.2f} inches".format(name, countryCode, height))
Print out using format method
EECS1015 – York University -- Prof. Michael S. Brown 87
Previous code
• Based on last lecture and these notes you should be able to
understand the code on the previous slide

• The code was written to be easy to read and understand

• You can make it more compact by combining some of the methods

• Also, f-string would have made a cleaner print statement, I used


.format() to make it work with Trinket.io

EECS1015 – York University -- Prof. Michael S. Brown 88


Putting it all together – Example 2
• A common task you'll face in writing software is converting between different
encoding formats.
• For example, consider the following two formats encoding the same information
• Format 1:
number1, number2, number3, …., numberM | letter1, letter2, …., letter3,letterN
For example:
"10, 20, 0, 14, 100, 0 | A, Z, D, E, F, G" <- assume extra spaces are allowed

• Format 2:
letter1;letter2;letter3;letter4;…;letterN*number1;number2;number3;number4;…;numberM
For example (string above converted for format 2)
"A;Z;D;E;F;G*10;20;0;14;100;0" <- extra spaces are not allowed

Task: Write code to input a string in format 1 and output it in format 2.

EECS1015 – York University -- Prof. Michael S. Brown 89


Solving task 2
• Let's think about one way to solve this problem
1. Input the string in format 1 (you can assume it is in the correct format)
2. Remove all the spaces since they are needed
How? Let's use the replace() method

3. Swap the string order around the "|"


How? We can use the .find() method to find the index of the character "|"
Then we can use splicing and concatenation to swap the order -- be careful to avoid the "|" (see code)

4. Convert the commas to semicolons


How? Let's use the replace() method

5. Output the string

EECS1015 – York University -- Prof. Michael S. Brown 90


Python Code
# first, input the string
msg = "Enter sequence of numbers separated with commas, \
Ask use to input string.
then a |, then a sequence of letters separated by commas." Note the "\" in this string is a way to have code
print(msg)
inputStr = input("Type string: ")
span multiple lines

# process string
# first, remove the spaces
inputStr = inputStr.replace(" ", "") # removes all spaces Step 2: Remove all the spaces.
# Now, let's find where the "|" is
# once we find it, split the string into two pieces
separatorIndex=inputStr.find("|") We find the position of "|"
letterString = inputStr[:separatorIndex] # all char up to index We splice up to the "|"
numberString = inputStr[separatorIndex+1:] # all chars after index, add 1 to avoid index char
outputString = numberString + "*" + letterString We splice after "|" to the end
Add together swapped with "*"
# convert commas to semicolor
outputString = outputString.replace(",", ";")
Replace all commas with semicolons between the strings.
print("Converted string in new format:")
print(outputString) Print the output

https://trinket.io/python/4f55754292

EECS1015 – York University -- Prof. Michael S. Brown 91


Example code running

Enter sequence of numbers separated with commas, then a |,


then a sequence of letters separated by commas.
Type string: 10, 2, 5, 8, 9, 0|A, B, Z, F, P

Converted string in new format:


A;B;Z;F;P*10;2;5;8;9;0

Input from the user is


shown in red.

EECS1015 – York University -- Prof. Michael S. Brown 92


Summary
• String manipulation are an important component of any programming
language.

• It is also useful to understand how to format strings to be able to


print out information.

• Now that you know the basics of inputting and printing data, we are
ready to move on to program flow control.

EECS1015 – York University -- Prof. Michael S. Brown 93

You might also like