Topic3 Strings FormattedOutput
Topic3 Strings FormattedOutput
Topic 3
Strings and Formatted Output
Fall 2021
Michael S. Brown
EECS Department
York University
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
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)
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.
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
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.
https://trinket.io/python/607dcc27d8
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
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
%_ 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:
https://trinket.io/python/277b38a727
%_ Notation
x = 100
x = "str {}, int {} float {}, formatted float {:.2f} ".format("hello", 10, 3.33333, 3.33333)
print(x)
https://trinket.io/python/1deb5f8349
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.
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.
https://trinket.io/python/9244ac6599
https://trinket.io/python/f7a8ebbb77
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)
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)
print(x)
print(y)
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)
print("x = " + x)
Forgot to include all the variables
print("y = " + y)
print("z = " + z)
needed by the format string
https://trinket.io/library/trinkets/27d3143433
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
Hello World
H
d https://trinket.io/library/trinkets/64085b59ae
'H'-' '-'d'
https://trinket.io/library/trinkets/98fed47917
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 ''
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)
https://trinket.io/python/9ebc771c9b
https://trinket.io/python/9909f017a5
x "CANADA" (string)
a "A" (string)
"ANA" (string)
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".
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.
"String object".method()
strVariable.method()
https://trinket.io/python/81517385ca
https://trinket.io/python/64698c5b03
Results:
1
3
2
https://trinket.io/python/7113b683ce
Results:
10
0
-1
https://trinket.io/library/trinkets/c79a4ba810
https://trinket.io/python/ab5f65b749
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
Results:
Space before.
Spaces before and after.
Space after.
https://trinket.io/python/61ef84f71a
Results:
This Is A Test.
This Is A Test.
This Is A Test.
https://trinket.io/python/6e9d3ca3e8
Results:
THIS IS A TEST.
THIS IS A TEST.
THIS IS A TEST.
https://trinket.io/python/64698c5b03
Results:
'HELLO WORLD!'
'HEXXO WORLD!'
'world'
Output Format: Welcome First Last (CA) - Your height is 74.13 inches.
# 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]
• 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
# 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
• Now that you know the basics of inputting and printing data, we are
ready to move on to program flow control.