Lecture 2 - Strings
Lecture 2 - Strings
Synopsis
This lecture will introduce you to the basics of strings. You will learn how to concatenate strings,
how to display them on the output console using single or multiple print() function arguments,
and how to incorporate escape sequences and bookends to format the output.
Learning outcomes
At the end of this lecture you will be able to:
• Understand what a string is.
• Describe the use of quotes.
• Practice accessing strings and string elements.
• Demonstrate the use of the % formatting operator in your applications.
• Differentiate methods from functions
• List and employ string related methods and functions.
Convention(s):
In programs, examples, or statements anything shown in bold font is the component the
user has to type.
Colors and bold fonts are used for reasons of emphasis and/or focus point.
Labs Note: In the in-class lab(s) you will be asked to code and run programs based on materials
covered on this, and previous lectures.
Output and Introduction to Strings
Strings in Quotes
Strings are series of alpha-numeric characters, that must be enclosed in quotes (single, double,
or triple), named “bookend”.
The only restriction is that if you start with one type of quotes the string must be terminated with
the same type.
There could be times where you would like to incorporate bookend in the output message. For
example, how could you output the message He said “hello!”?
These are the rules you must follow:
1. If you start/end with triple-quotes bookend you can use single and double quotes as part
of the string.
2. If you start/end with double-quotes you can use single or triple quotes as part of the
string.
3. If you start/end with single-quotes you can use double quotes as part of the string, but
not triple.
4. Escape sequences allow you to incorporate bookend in a string
Escape Sequences
Escape sequences
1. Allow you to place special characters in a string.
2. Consist of two characters, the first one always being the back-slash (\) and another one
following immediately after, like \n.
The back-slash (\) tells the computer to treat the character the follows it in a
special way.
Sequence Function
Today's Lecture.
>>>print("He said \"Come Back!\" ") String incorporates double quote
bookend
He said "Come Back!"
>>>print('Dir1\\Dir2') String incorporates backslash
Dir1\Dir2
>>>print('This is the first Python course') Normal, single quotes bookend
>>>print('''Petros 'D' "Passas“ ''') Triple quotes bookend and single and
double quotes are used as part of the
Petros 'D' "Passas" string
The following table shows examples of string concatenation using “+” symbol or comma.
>>>print('Hello! How ar‘ + 'e you ?') Concatenate two strings using +, provides no
space.
Hello! How are you ?
1 2 3 4.5 6.9
3.3
You cannot mix data types. If you mix a string with an integer or floating point number, Python
will see it as an ambiguous expression, and gives an error message. In the command below,
the statement tries to add an integer (3) and a string (very), and as you can see the Interpreter
prompts an error.
>>> 3 + 'very'
If sep is used in a print statement, it will separate the arguments using the characters of
choice. Some examples using the sep parameter are displayed below.
The table below includes examples of statements using the keyword “sep”, their respective
output, and comments on the right column.
Examples using sep and their output Comment
>>>print('Hello', 'Petros', '!', sep='') No space between the fields
HelloPetros!
>>>print('Hello ', 'Petros','!', sep='') Note the implicit space after “Hello “
Hello Petros!
Hello--How--are--you?
Hello****How****are****you?
Use of end = ‘string or character’
If at the end of the argument of the print statement you include the reserved word ‘end=’
followed be a character or a string, the character or the string will be appended at the end of the
argument.
Example of statement using keyword end, its output and comment.
print('Hello!', 'How', 'are','you?',end='****') **** were appended
Repeating Strings
You can have a string to be repeated multiple times by using the following general syntax
“string” *n or n * “string”
print(‘Bye’ * 3) ByeByeBye
>>>3 * ‘Bye’ ByeByeBye
Exercises
2. Write a single print statement that will produce the following output
1. Windows
2. Linux
3. OS2
4. Write a single statement that will add the values of 5 and 8 and display the sum.
The output should look as the following:
Exercise Answers
1. print(' His mother said: "Don\'t forget to have breakfast and wash the dishes" ')
2. print('1. Linux \n2. Windows \n3. OS2')
3. print('First name\t\tLast Name\t\tID')
4. print('The sum of: 5 + 8 =', 5+8)
Accessing String Elements
A string is stored as an array. In Python an array is known as a list. To access the list’s
elements you need to use the subscripted notation.
Element Content
str[0] P
str[1] e
str[2] t
str[3] r
str[4] o
str[5] s
You can use the print() function and print the entire string, part of the string, or elements of the
string.
Function Operation
print (str[2:]) Prints string starting from 3rd character to the end
print (greeting[0]) H
Syntax Syntax
function(parameters) object.method( ) or
object.method(parameters)
The main essence: Methods are associated with object instances or classes; functions aren't.
Using Methods
As you have seen earlier, the general syntax to use methods is:
object.method(parameters)
String Methods
>>> print(first.lower())
petros
print(book.title())
First Book In Python
print(book.replace('First', 'Best'))
Best book in python
Exercises
1. Write a program in which you assign to a variable the word “Congratulations” and then extract
the letters and print the word ‘Goal’. Note upper case ‘G’.
2. Revise the above program that will use the “*” symbol to print the sentence:
Goal Goal Goal de Barcelona.
Answers
1.
str1 = 'Congratulations'
str2 = (str1[3].upper())+str1[1]+str1[5]+str1[8]
print(str2)
2.
str1 = 'Congratulations'
str2 = (str1[3].upper())+str1[1]+str1[5]+str1[8]
print(str2)
print(3 * (str2 +' '), 'de Barcelona')