Good day. This passage of our cycle is devoted to practical exercises on sequential collections: lists and strings. We will see how to perform various less or more difficult operations. So, at last, we're going to do something useful – one may say – which is coding. In other words let's turn to the "Practical Side of the Force" 🙂

In the previous two passages we presented quite a lot of knowledge: definitions, syntax elements, rules of conduct. This knowledge will allow us to efficiently use sequences, i.e. ordered sets of elements in Python.

What do we already know?

First of all: we know the techniques of slicing; thanks to this, we are able to extract the fragment of the sequence that interests us.

Second: we learned the tools (methods and functions) that allow us to perform various operations on the sequences. This is already a considerable capital of knowledge. Let's try it out by doing a few exercises.

Note: As for methods and functions, we will focus on the methods dedicated to strings. In the future, it will also be worth getting acquainted with methods dedicated to lists.

Warming-up

Let's warm up with a very nice example that many people will probably associate with childhood and times when we played encrypted messages. The easiest way to encrypt is to insert one random letter between the letters of an existing string. Here is an example of an encrypted message:

'Wren scronduet tiane YPayntahuorn'

To decode it, we need to read every second letter from the string. How to do it in Python? By defining the value of the "step" in slicing notation.

To decrypt the message given earlier, name the sequence with a letter (e.g. y) and then make a slice with the step value = 2.

y='Wren scronduet tiane YPayntahuorn'

y[::2]

For those who want to learn again what y[::2] means, we recommend that you move back for a minute to Passage 6, Appendix: Slicing — extended version.

When you perform this Python exercise, you will get a decrypted message:

'We code in Python'

Another nice trick is to re-write the string backwards (back to start). How can you get it?

Giving a negative step value:   S[::-1]

Let's see how it works

S='banana'

S[::-1]

Output:  'ananab'

Note: The above exercises are not only fun. These types of tasks appear en masse at various types of exams, tests and interviews. It's really worth training them for a while.

Do-it-yourself (examples and exercises)

Cutting-off boundary characters

Example

Write a script that will cut-off the last character in the given string.

Solution:

txt='My car.'

new_txt=txt[:-1]

print(new_txt)

Output:

'My car'

D‑I-Y

Your program is supposed to ask the user to enter any proverb. However, there is a problem — users enter them in asterisks. Suggest a code to get rid of the asterisks, for example:

* A friend in need is a friend indeed * → A friend in need is a friend indeed

Another exercise

Write a script which will cut the last two characters from the given sequence. We raise difficulty level here: this time you can't use negative indexing. How can you handle it in a different way?

Suggestion: use the function len()

Producing a new sequence

Example

Using negative slice notation, "produce" the word ange from the word oranges

Solution:

a='oranges'

print(a[-5:-1])

D‑I-Y

Write the script that from the list

['Ferrari', 'Aston Martin', 'Bentley', 'Porsche', 'Bugatti', 'Lamborghini', 'BMW', 'Mercedes', 'Jaguar']

will produce a list

['Aston Martin', 'Porsche', 'Lamborghini', 'Mercedes']

Hint: discard extreme list items, and then select every other item.

Assigning multiple items at once

Example

You can assign several new elements to a sequence (in place of several old ones) with one command.

a=[1, 2, 3, 4, 5, 6]

a[:3]=[7, 8, 9]

print(a)

Output: [7, 8, 9, 4, 5, 6]

D‑I-Y

You have a list of colors:

colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple']

Modify it to the following form:

colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']

Assigning Multiple Items Simultaneously — continued

Example

Create a list of five single letters. Replace every second item in the list with x.

Solution: First, let's count how many 'x' letters we will need. Three, right? Why? Because the first, third and fifth elements will swap.

L = ['t', 'i', 'g', 'e', ​​'r']

L [:: 2] = ['x', 'x', 'x']    # we give a three-element sequence to replace existing letters

print (L)

Output:

['x', 'i', 'x', 'e', ​​'x']

D‑I-Y

From the existing list K = [1, 2, 3, 4, 5, 6] create a new list that returns the odd elements unchanged and the even elements as half the initial values. The target list should therefore be K = [1, 1, 3, 2, 5, 3]

Hint: you need to create a substitution list that will do the same as in the previous example. We suggest that you use a list consisting of the following elements: [1, 2, 3]. The values ​​of these elements are half of three consecutive even numbers: 2, 4, 6.

We think this is enough training "cutting techniques"? All right. Now it's time to practice the methods dedicated to string data.

Removing selected characters from a string

Example

Write a script that removes spaces in the text. For example: user specifies New Age, program converts to: NewAge.

Here, as we mentioned, the greatest difficulty is finding the right method. Then we're "over the hump". Well, we searched, searched and finally found:  the method we're going to use here is called replace(). It replaces the selected phrase (part of a string) with another phrase.

The replace() method has a fabulously simple syntax:

txt.replace (oldvalue, newvalue)

Example:

txt = 'I like coffee'   # lets replace coffee with tea in this text

txt.replace ('coffee', 'tea')

Output: 'I like tea'

When we want to remove the selected character — so that NOTHING appears in its place — it is enough to specify the second parameter in the syntax of the replace method as empty quotation marks: ''
(open and closed single quotation marks).

Ok, let's get back to our task. So, the newvalue will be just nothing, and the oldvalue (of course) will be a space — enclosed in quotation marks, i.e. ' '

Let's see how it works:

txt='New Age'

txt.replace(' ', '')

Output: 'NewAge'

It worked brilliantly as we expected.

D‑I-Y

Write a script that replaces the doubled dots in the text with a single dot.

For example:

'This is a famous clock in London.. It is called Big Ben..'  →  'This is a famous clock in London. It is called Big Ben. '

First letter capitalization

Write a script that changes the first letter from lowercase to uppercase in the string. For example, the user enters 'berlin', the program returns 'Berlin'.

Hint: use the capitalize() method

DIY — a bit more difficult

Ask the user for a string of his first and last name.

Split the user-supplied string into two strings (this time you have to find the correct method yourself). Assume that the separator is a space.

Example: 'John Smith' → 'John', 'Smith'

Then, perform an operation that will shorten the first string to the first letter. Finally, give the command to print the first letter of the first name, period and last name.

Desired output: J. Smith

Hint: once you've found (and used) the correct method to split one string into two, take a close look at the output. These two newly formed strings were returned to you in the form of a two-item list:

['John', 'Smith']

You agree that it is much more convenient than if you got them in bulk, don't you?  When you buy apples at a market stall, it is also more pleasant for you to get them in a paper bag, not in bulk, right?

But let's concentrate now; to shorten the name John to the first letter: J, we must:

• get the first item from a two-element list

• get the first element from this element (first character).

The searched element is therefore nested in nature, that is, it is an element of a sequence which, in turn, is an element of a larger sequence. How to access a nested item? When you want to get the so-called nested access, e.g. to the first letter of a word, which is the first element of the list X, you write: X[0][0]

Appendix: Exercise Solutions

Cutting-off boundary characters

Solution (exercise 1)

X=input('Enter quotation: ')

Y=X[1:-1]

print(Y)

Solution (exercise 2)

a=input('Enter any string of characters: ')

x=len(a)-2

b=a[:x]

print(b)

Producing a new sequence

Solution:

L=['Ferrari', 'Aston Martin', 'Bentley', 'Porsche', 'Bugatti', 'Lamborghini', 'BMW', 'Mercedes', 'Jaguar']

print(L[1:-1:2])

Assigning multiple items at once

Solution

colors=['red', 'orange', 'yellow', 'green', 'blue', 'purple']

colors[5:]=['indigo', 'violet']

print(colors)

Assigning Multiple Items Simultaneously — continued

Solution

K=[1, 2, 3, 4, 5, 6]

M=[1, 2, 3]

K[1::2]=M

print(K)

Removing selected characters from a string

Solution:

txt='This is a famous clock in London.. It is called Big Ben..'

txt.replace('..', '.')

First letter capitalization

txt='berlin'

txt.capitalize()

DIY — a bit more difficult

Solution

The method you should use is called split(). Its syntax is easy to remember — you write the name of the string to be split, a period, the word split, and in parentheses (in quotation marks) the character on which to split. E.g.:

txt = 'John is clever, Anya is clever, Mike is clever'

# we want the split to occur where a comma and a space appear, so:

new_txt = txt.split (', ')

print (new_txt)

Output: ['John is clever', 'Anya is clever', 'Mike is clever']

# the result was returned as a list

Note: If you do not indicate any of the character "on which to split", i.e. write txt.split(), Python will split the string wherever there is a space.

So we are now ready to do the job. Here is the code:

txt=input('Enter your full name: ')

X=txt.split()

p=X[0][0]

q=X[1]

print(p+'. '+q)