You are on page 1of 44

WORKING WITH DATA

DATA

1/7/20XX Pitch deck 2


ESCAPE SEQUENCES

Nobody likes to write long forms of words, so here comes apostrophe.


Be careful, though, when using an apostrophe in strings in Python, you
might get an error message.

Let's take a look at the example below:

The sentence seems to look fine, but Python will show you an error message
«EOL while scanning string literal».
Why did that error occur? The abbreviation "EOL" stands for "End-of-line" and it
means that Python went through the text and didn't find the end of the string. The
sentence was divided into two parts. The first one is "That" and the second one
is "s my car".
ESCAPE SEQUENCES
A backslash can be used in a combination with another symbol to do some
particular things.
For example, if you use \b in the middle of the string and then try to print it,
you won't see the character before \b. The combination \b means a
backspace character:

Take a look at some other escape sequences:


•\n – newline
•\t – horizontal tabulation
•\r – moves all characters after \r to the beginning of the line, overwriting as
many characters as moved.
The use of escape sequences in a string is always the same. Nevertheless, we
will give more examples in the next section.
So, what if you need to print the backslash itself?

4
ESCAPE SEQUENCES
Now if you want to print text that contains \, you can double it. For example, this is
useful when you need to print literally \n, because print('\n') will only output a new
blank line. Double backslash will help you in such situations!

And you can also write:

Why is everything correct in such a case? Our string with \ printed correctly,


because \m is not an escape expression. Therefore, no formatting has occurred. One
more example:

The function repr() returns a printable representation of this string, thus, escape


sequences are visible.

When we want to know the length of a string, escape sequences are also taken into
account:

Pitch deck
WHAT IS AN ESCAPE SEQUENCE?

To avoid the described problem you should use escape


sequences.

All escape sequences start with a backslash \, which is


interpreted as an escape character. A backslash indicates
that one or more characters must be handled in a special
way or that the next character after it has a different
meaning.

Add an escape character to our example and see that the


quote is now interpreted as the literal symbol of a single
quote without any errors.
OTHER EXAMPLES
• Let's consider an example with the escape sequence \n

• The \n combination starts a new line, so you will see the following output:

• The next example shows the escape sequence \t. As it was said above, \t is used for tabulation. If you put it in the middle of a string,
the two parts of the string will be divided by some blank space that is called tabulation. It is quite useful when you work with a text.

• Another escape sequence that can be useful while you are working with text is \r. The common name for this escape sequence is a
carriage return. It moves characters after \r to the beginning of the line, replacing the exact number of old characters. That is, if the
length of the string is longer before this escape sequence, then only the required number of characters is rewritten.
OTHER EXAMPLES
• Let's consider an example with the escape sequence \n

• The \n combination starts a new line, so you will see the following output:

• The next example shows the escape sequence \t. As it was said above, \t is used for tabulation. If you put it in the middle of a string,
the two parts of the string will be divided by some blank space that is called tabulation. It is quite useful when you work with a text.

• Another escape sequence that can be useful while you are working with text is \r. The common name for this escape sequence is a
carriage return. It moves characters after \r to the beginning of the line, replacing the exact number of old characters. That is, if the
length of the string is longer before this escape sequence, then only the required number of characters is rewritten.
OTHER EXAMPLES
• Please note that the string length remains the same!

• Escape sequences are simple to use, aren't they? Let's talk more about the length of strings. For example:

• After calling the len() function, we can see that the length of the string with an escape sequence (in this case \n) is greater.
• Be careful while working with strings because the function print() doesn't show escape sequences.
EXERCISE

Write your answer in the chat box


EXERCISE

What symbol indicates an escape sequence?


EXERCISE

Which escape sequence does not exist?


EXERCISE

Find the sentences which can be printed without an error


SPLIT AND JOIN

• In Python, strings and lists are quite similar.


• Firstly, they both pertain to sequences, although strings are limited
to characters while lists can store data of different types. In
addition, you can iterate both over strings and lists. However,
sometimes you need to turn a string into a list or vice versa.
• Python has these kinds of tools. The methods that will help you to
accomplish this task are split(), join(), and splitlines().
SPLIT A STRING
• The split() method divides a string into substrings by a separator. If
the separator isn't given, whitespace is used as a default.
• The method returns a list of all the substrings and, notably, the
separator itself is not included in any of the substrings.
SPLIT A STRING
• You can also specify how many times the split is going to be done with
the maxsplit argument that comes after the separator. The number of
elements in the resulting list will be equal to maxsplit + 1.
• If the argument isn't specified, all possible splits are made.
SPLIT A STRING

• If the separator doesn't occur in the string, then the result of the method is a list with the original string as its only
element:

• Thus, in all cases split() allows us to convert a string into a list.


• It may also be useful to read input directly into several variables with split():

• It's pretty efficient when you know the exact number of input values. In case you don't, it's likely to result
in ValueError with a message telling you either that there are too many values to unpack or not enough of them.
JOIN A LIST

• The join() method is used to create a string out of a collection of strings.


• However, its use has a number of limitations. First, the argument of the method must be an iterable object with strings
as its elements. And second, the method must be applied to a separator: a string that will separate the elements in a
resulting string object. See below the examples of that:
JOIN A LIST

• Note that this method only works if the elements in the iterable object are strings. If, for example, you want to create a
string of integers, it will not work. In this case, you need to convert the integers into strings explicitly or just work
with strings right from the outset.
SPLIT MULTIPLE LINES

• The splitlines() method is similar to split(), but it is used specifically to split the string by the line boundaries.
• There are many escape sequences that signify the end of the line, but the split() method can only take one separator.
So this is where the splitlines() method comes in handy:
SPLIT MULTIPLE LINES

• The method has an optional argument keepends that has a True or False value. If keepends = True linebreaks are
included in the resulting list:

• You can also use several string methods at once. It is called chaining, and it works because most of the string methods
return a copy of the original string:
EXERCISE

• What is the name of calling multiple methods at once?


EXERCISE
STRING FORMATTING

• There are certain situations when you want to make your strings kind of "dynamic", i.e. make them
change depending on the value of a variable or expression.
• For example, you want to prompt the user for their name and print the greeting to them with the
name they entered. But how can you embed a variable into a string? If you do it in the most intuitive
way, you'll be disappointed:

• The output will be:


STRING FORMATTING

• Luckily, Python offers a large variety of methods to format the output the way you want and
we'll concentrate on the main two:
• Formatted string literals
• The str.format() method
• Earlier the % operator was in use. This built-in operator was derived from C-language and was
used in some situations in the following way:

• Thus, the variable to the right of % was included in the string to the left of it. If we'd wanted to
divide 11 by 3, the / operator would have returned a float number with a lot of decimal places.
STRING FORMATTING

• With % character, we could control the number of decimal places, for example, reduce their
number to 3 or 2:

• For every operation, you had to know plenty of specifiers, length modifiers and conversion
types. A huge variety of extra operators led to some common errors. That's why more modern
and easy to use operators were introduced. Progress never stops, you know!
• Formatting your strings also makes your code look more readable and easily editable.
STRING FORMATTING
• Python uses C-style string formatting to create new, formatted strings. The "%" operator is
used to format a set of variables enclosed in a "tuple" (a fixed size list), together with a
format string, which contains normal text together with "argument specifiers", special
symbols like "%s" and "%d".
• Let's say you have a variable called "name" with your user name in it, and you would then
like to print(out a greeting to that user.)

• To use two or more argument specifiers, use a tuple (parentheses):


STRING FORMATTING
• Any object which is not a string can be formatted using the %s operator as well. The string
which returns from the "repr" method of that object is formatted as the string. For example:

Basic Argument Specifiers


• %s - String (or any object with a string representation, like numbers)
• %d - Integers
• %f - Floating point numbers
• %.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of
the dot.
• %x/%X - Integers in hex representation (lowercase/uppercase)
str.format() method

• The operation of the method is already described in its name: in the string part, we introduce
curly braces as placeholders for variables enlisted in the format part:

• The expressions are put instead of braces in the order they were mentioned:
str.format() method

• You can use the same variable in one string more than once if it's necessary. Furthermore, you
can address the objects by referring to their positions in curly braces (as usual, the numbering
starts from zero). Attention: the order you choose can be very important. The following two
codes:

• And

• will have different outputs:


• The second output sounds really weird, doesn't it?
• If you've mentioned more variables than needed in
• the format part, the extra ones will just be ignored.
str.format() method
• We can also use keywords to make such strings more readable. Don't forget that you can easily break the lines! For
example:

• Note that you can also mix the order as you want if you use keywords. Here's the formatted string:

• Also, you can combine both positional and keyword arguments:

• Keep tabs on the order of your arguments, though:

• The last code snippet resulted in SyntaxError, since positional arguments are to be mentioned first.
Formatted String Literals
• Formatted string literals (or, simply, f-strings) are used to embed the values of expressions inside
string literals. This way is supposed to be the easiest one: you only need to put f before the string and
put the variables you want to embed into the string in curly braces. They are also the newest feature
among all string formatting methods in Python.

• If you print this short string, you'll see an output that is five times longer than its representation in
code:
Formatted String Literals
• You can also use different formatting specifications with f-literals, for example rounding decimals
would look like this:
Exercise
What will be the output of this code?
Exercise
How many decimal places will this code return?

2
(ASSIGNMENT) – you can discuss with your classmates
• The output should be user-friendly, but the code part is also important. Well-structured and readable code is very important for being a
good programmer. Now it's up to you to decide, which formatting method to choose.
• Imagine you need to compose a dynamic URL for every certain user with user-specific details. Suppose, you want to send different
URLs for every user, depending on their name and profession. The base would be something like
• "http://example.com/*nickname*/desirable/*profession*/profile", where nickname and profession are prompts from a user and are
dynamic.
• Read the nickname and profession of the user from the input and print a user-specific URL. Don't bother about any rules of composing
the URLs and just use raw input to accomplish the task.
HO1_3SECTIONCLASSNUMBER

• Save the project as ZookeeperHO1_3SECTIONCLASSNUMBER


• Create 3 Python Files with the following names:
a. Part1
b. Part2
c. Part3
• Upload the files in your Hands On Activity folder not later than
September 24, 2021
ZOOKEEPER Part 1
Description:
• There are many animals in the zoo, and all of them need care. The animals must be fed, cleaned, surrounded
by their kin, and kept happy. That is a difficult task for our large zoo, so one of your employers has
suggested a more convenient way to keep track of everything. She wants to be able to pull up a video feed of
any animal in the zoo with the help of a program. Being able to check on each habitat would help the
zookeepers take care of our furry friends more efficiently!
• In this project, you will create a program that helps the zookeepers check on the animals and make sure that
they're doing well. Your product will be able to process commands from the zookeepers and display the
animals on a monitor.
Objectives:
• To begin with, you will develop a simple printer. Your program should display the text from the output
example.
Example Output:
ZOOKEEPER Part 2 Example
Your output should contain the following ASCII image:
Switching on the camera in the camel habitat...
 ___.-''''-.
Description
/___  @    |
• One of the most important parts of working with animals is ',,,,.      |          _.'''''''._
keeping an eye on them. We need to see the animals on the      ’      |         /            \
screen to know how they are doing, right? Now we are      |      \     _.-'              \
ready to print something awesome: an image of an animal!      |       '.-'                   '-.
Objectives      |                                ',
     |                                  '',
• For the second stage, you will need to develop an animal       ',,-,                            ':;
printer. Your program should display the animal identified            ’,, |  ;,,                  ,' ;;
in the code field.                !  ;  !'',,,’ , ',,,,’ !   ;   ;:
• Please, don't remove the r character at the start of the code               :  ;   ! !        ! ! ;   ;   :;
template. It's a part of the string and it's important. So, the               ;  ;   ! !       ! !   ;  ;   ;,
string should start with r""" sequence. This “r” at the              ;  ;    ! !      ! !    ; ;
beginning stands for “raw” and allows various characters to              ;  ;    ! !      ! !      ; ;
be used in a string without escaping. For instance, “\” in a            ; , ,     !,!    !,!     ;,;
non-raw string should be escaped as follows: “\\”.          /_I      L_I    L_I  /_I
Look at that! Our little camel is sunbathing!
EXAMPLE
ZOOKEEPER Part 3
Description
• The third stage requires you to increase the capabilities of your software. Now it should be able to
recognize the number of a specific habitat from the input and show the animals living there.
• Add all of the variables from the template to a single variable with the list type. The order of
variables matters: they must appear on the list in the order in which they're defined in the code. The
list must contain all of the variables with no duplicates.
Objectives
• In this stage your program should:
1. Ask for the number of the desired habitat using the following phrase: Please enter the number of the
habitat you would like to view:
2. Use the input number as an index of your habitats to print its content.
3. End with the following phrase:
EXAMPLE 1 The greater-than symbol followed by a space (> ) represents
the user input. Notice that it's not part of the input.
EXAMPLE 2 The greater-than symbol followed by a space (> ) represents
the user input. Notice that it's not part of the input.
ASYNCHRONOUS TASK 9-23-2021

• Go to 1st Quarter -> Class Materials -> PowerPoint Presentations ->


Open Working with Data
• Resume the slide show from where we stopped last meeting. You can
start from the beginning if you need to review
• Try out the activities and examples provided in your PyCharm
• Do the assignment
• Work on the Hands - On Activity 3 and follow the instructions
provided
• Periodical Test will be on September 30, 2021

You might also like