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

Lecture 2 - Strings

This lecture introduces strings and how to manipulate and format string output. Key topics covered include concatenating strings, using escape sequences to include special characters in strings, and using print formatting options like sep and end to control string output display.

Uploaded by

godswille2020
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Lecture 2 - Strings

This lecture introduces strings and how to manipulate and format string output. Key topics covered include concatenating strings, using escape sequences to include special characters in strings, and using print formatting options like sep and end to control string output display.

Uploaded by

godswille2020
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Lecture 2

Output and 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.

The following table shows the escape sequences.

Sequence Function

\\ Prints one backslash


\’ Prints a single quote
\” Prints a double quote
\n Prints a new line (moves the cursor to the next line)
\t Prints a tab (moves the cursor one tab)
\a Sounds the system bell, but works only if you run your program from the
OS and not through the IDLE
Incorporating Bookend
In the table below, you see examples of how you can incorporate bookend, backslash using
escape sequences, and strings in quotes.

Statement and its output Comment


>>>print('Today\'s Lecture.') String incorporates single quote bookend

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

This is the first Python course

>>>print("This is the first Python course") Double quotes bookend

This is the first Python course

>>>print('''This is the first Python course''') Triple quotes bookend

This is the first Python course

>>>print('''Petros 'D' "Passas“ ''') Triple quotes bookend and single and
double quotes are used as part of the
Petros 'D' "Passas" string

>>>print(‘ “Petros” ‘) Single quotes bookend and use double


codes as part of the sting
“Petros”
String Concatenation
Concatenation means combining two or more strings.
You can use the "+" or the comma (,) to join strings together. If you use a ",", then you will
have a space in between the strings you joined.
If you use a "+", then the strings will be strung together with no space. You will need to
literally add a space if you need to separate them.
For numbers:
a. If you use the "+" to join integers and floats together, you will perform an arithmetic
operation.
b. If you use the ",", it will print them out separately, with a space.

The following table shows examples of string concatenation using “+” symbol or comma.

Statement and its output Comment


>>>print('Hello','Petros') Concatenate two strings using comma,
provides space.
Hello Petros

>>>print('Hello! How ar‘ + 'e you ?') Concatenate two strings using +, provides no
space.
Hello! How are you ?

>>>print('Hello', 5) Concatenate a string and a number using


comma
Hello 5

>>>print(1, 2, 3, 4.5, 6.9) Concatenate numbers using comma

1 2 3 4.5 6.9

>>>print(1 + 2.3) + adds numbers

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'

Traceback (most recent call last):


File "<input>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str‘
Traceback error: Occurs when the code is being executed
The next two lines show you where the error occurred.
To eliminate the default space between fields you can use either one of the following:
1. Use the concatenation symbol “+” between the two fields you need to eliminate the
space.

Statement and its output Comment


>>>print('Hello', 'Petros', '!') As you can see at the output, there is an
unwanted space between the word
Hello Petros ! “Petros” and “!”.
This is because the comma was used

>>>print('Hello', 'Petros'+ '!') In this output the space is eliminated,


because “+” was used
Hello Petros!

2. Use a keyword parameter named sep, as a final field.

sep = ‘character, or string of choice’

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.

sep = ’‘ gives no space


sep = ’ ‘ adds one space between the fields
sep = ’ ‘ adds 3 spaces between the fields
sep = ‘!!!’ Inserts !!! between the fields

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!

print('Hello','How', 'are', 'you?', sep='--') Inserts – between the string fields

Hello--How--are--you?

print('Hello','How', 'are', 'you?', sep='****') Inserts ****

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

Hello How are you?****


print('How are you', 'Petros',sep='????',end='***' Use both end= and sep=
How are you????Petros***

print() Generates New Line


As mentioned earlier, the print() function will automatically generate a new line.
The end = ’something’ will overwrite the new line generation.
The use of a print() function with no arguments will generate a blank line.

Statements of print() using argument, no argument, and end=’string’


Statement and its output Comment
print('one', 'two') Prints one, gives a space, then prints two
print('three', 'four')
and moves to the next line.
Then prints three, gives a space, prints
print() four and moves to the next line
The print() generates a blank line.
print('Hello!','How', 'are', 'you?', end='****')
print('I am fine.','Thank you.')
It then prints Hello! How are you?****
But does not create a new line because of
one two
the end=****, so on the same line prints
three four
I am fine. Thank you.
Hello! How are you?****I am fine. Thank you.

Repeating Strings
You can have a string to be repeated multiple times by using the following general syntax

“string” *n or n * “string”

where n is the number of times you want the string to be repeated.

print(‘Bye’ * 3)  ByeByeBye
>>>3 * ‘Bye’  ByeByeBye
Exercises

1. Write a print statement that will produce the following output


His mother said: "Don't forget to have breakfast and wash the dishes"

2. Write a single print statement that will produce the following output
1. Windows
2. Linux
3. OS2

3. Write a statement that will print the following as it shown below


First name Last Name ID

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:

The sum of: 5 + 8 = 13

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.

Assume you have a string named str = “Petros”.


The first element (character) of the string is always stored at index[0]. So, the string str is stored
as shown in the table below.

Element Content

str[0] P
str[1] e
str[2] t
str[3] r
str[4] o
str[5] s

Printing String and String Elements

You can use the print() function and print the entire string, part of the string, or elements of the
string.
Function Operation

print (str) Prints complete string

print (str[0]) Prints first character of the string

print (str[2:5]) Prints characters starting from 3rd to 5th

print (str[2:]) Prints string starting from 3rd character to the end

print (str * 2) Prints string two times

print (str + "TEST”) Prints concatenated string

Examples of Printing String and String Elements


Statement Output

greeting = "Hello dear Mia"

print (greeting) Hello dear Mia

print (greeting[0]) H

print (greeting[6:14]) dear Mia

print (greeting[6:]) dear Mia

print(greeting * 2) Hello dear MiaHello dear Mia

print(greeting + " Passas") Hello dear Mia Passas


Manipulating Strings for Output
Python includes a number of functions and methods that can be used with strings.
Because you are going to be using functions and methods, you need to know the basic
differences between a function and a method. In a later chapter you will learn functions in
details.
A function is a piece of code that: Objects are instances of a class
1. Has a name followed by ( ) Objects have associated methods.
2. Is called by name.
3. It may accept data to operate on (i.e., A method is a piece of code that:
the parameters) and 1. Has a name followed by ( )
4. can optionally return data 2. Is called by name that is associated
with an object.
3. It is implicitly passed for the object for
which it was called
4. It is able to operate on data that is
contained within the class
5. It may take additional parameters

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)

Some methods may not accept parameters.


Many of the names in the list start and end with two underscores, like __add__. These are all
associated with methods and pieces of data used internally by the Python interpreter. You can
ignore them for now.

String Methods

1. s.lower(), s.upper() -- returns the lowercase or uppercase version of the string or


character
2. s.strip() -- returns a string with whitespace removed from the start and end
3. s.isalpha()/s.isdigit()/s.isspace()... -- tests if all the string characters are in the various
character classes
4. s.startswith('other'), s.endswith('other') -- tests if the string starts or ends with the
given other string
5. s.find('other') -- searches for the given other string (not a regular expression) within s,
and returns the first index where it begins or -1 if not found
6. s.replace('old', 'new') -- returns a string where all occurrences of 'old' have been
replaced by 'new'
7. s.split('delim') -- returns a list of substrings separated by the given delimiter. The
delimiter is not a regular expression, it's just text. 'aaa,bbb,ccc'.split(',') -> ['aaa', 'bbb',
'ccc']. As a convenient special case s.split() (with no arguments) splits on all whitespace
characters.
8. s.join(list) -- opposite of split(), joins the elements in the given list together using the
string as the delimiter. e.g. '---'.join(['aaa', 'bbb', 'ccc']) -> aaa---bbb---ccc
9. s.title() - returns a copy of the string in which first characters of all the words are
capitalized.
10. s.center(width) – returns a copy of s centered within the given number of columns
11. s.ljust(width) – returns a left-justified sting s with spaces added to fill out the width
12. s.rjust(width) -- returns a right-justified sting s with spaces added to fill out the width
Run the following examples (noted in bold face) at the Shell and observe the output.

>>> first = input('Enter your fist name: ')


Enter your fist name: >? Petros
>>> last =input('Enter your last name: ')
Enter your last name: >? Passas

>>> print(first, last)


Petros Passas

>>> print(first.upper(), last.upper())


PETROS PASSAS

>>> print(first, last.upper())


Petros PASSAS

>>> print(first.lower())
petros

book = input('Enter the book title: ')


Enter the book title: >? First book in python
print(book)
First book in python

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')

You might also like