{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Exercises\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise 1.1 \n", "What does `myString[0:10:2]` do? \n", "What could the `2` mean in that context?\n" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "02468\n", "019876543210\n" ] } ], "source": [ "myString = '012345678910'\n", "print(myString[0:10:2])\n", "# The 2 is the step/increment between each selected index in the sequence. In this case, every 2nd letter is kept.\n", "# This allows the following neat trick to reverse a string: have steps of -1\n", "print(myString[::-1])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "## Exercise 1.2 \n", "I am trying to make a division. Could you make my code work?" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3.0\n" ] } ], "source": [ "a=12\n", "b='36'\n", "# The problem here, is that \"a\" in an int(), and \"b\" is a str().\n", "# -> we have to convert \"b\" to a number type (int or float) in order for the division to work.\n", "division = int(b)/a\n", "print(division)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "## Exercise 1.3 \n", "1. Put your favorite quote in a string variable." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "myQuote=\"- Regarde-moi, mon cher, et dis quelle espérance Pourrait bien me laisser cette protubérance !\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "2. Find a way to replace all spaces by '@' in the quote.\n", "Since `myQuote` is a string, we look at `help(str)` to search for methods available for string objects. We can see that there is a `replace()` method that allows replacing characters within a string." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "- Regarde-moi, mon cher, et dis quelle espérance Pourrait bien me laisser cette protubérance !\n", "-@Regarde-moi,@mon@cher,@et@dis@quelle@espérance@Pourrait@bien@me@laisser@cette@protubérance@!\n" ] } ], "source": [ "modifedQuote = myQuote.replace(' ','@')\n", "print(myQuote)\n", "print(modifedQuote)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "