================= Data type: string ================= .. _strings: .. index:: string, data type: string .. |a| image:: /images/all/python-basics/text-100.png :width: 100px Objectives ========== .. tabularcolumns:: | c | l | :border: none +-------+-------------------------------------------------------------------------+ | |a| | Every programming language is using strings as a data type. | | | The Python way to handle strings, is shown in this station. | +-------+-------------------------------------------------------------------------+ Instructions ============ :Tasks: 1. Save the following text, line by line into variables: .. ifconfig:: language == 'en' :: "Shall I compare thee to a summer's day? Thou art more lovely and more temperate..." Lines from Shakespeare's Sonnet 18. .. ifconfig:: language == 'de' :: "Soll ich dich einem Sommertag vergleichen? Er ist wie du so lieblich nicht und lind;..." Zeilen aus dem Sonnet 18 von Shakespeare 2. Return the values of all variables with the print-Function. Don't forget the empty line. Properties and rules ==================== - A string is enclosed in the following characters: single quotation, double quotation and triples of the quotation signs. - Strings are immutable, if you change a string, the computer has to reserve new memory and afterward release the old memory. - Each character is callable with an index. The index counting starts at zero. More hints about strings kann be found at: .. ifconfig:: language == 'en' `Wikipedia: String (computer science) `_ .. ifconfig:: language == 'de' `Wikipedia: Zeichenketten `_ Assign strings ============== Each variable get's own value. .. ifconfig:: language == 'en' todo: find a good equivalent to the german version... .. ifconfig:: language == 'de' :: a = "Fliegen " b = 'fliegen!' c = '' # an empty string print(a, b, c) Concatenate strings ------------------- Building longer Strings from substrings, is an often used technique. .. ifconfig:: language == 'de' :: a = "Fliegen" b = "fliegen" c = "Wenn " + a + " hinter " + a + " " + b + ",\n" c = c + "dann " + b + " " + a + " " + a + " hinterher!" print(c) :Hint: The same result can be achieved with other data types :ref:`tuple ` and :ref:`list `. Extract parts of string ----------------------- This task is possible with the slicing operator. This operation is available for all sequence data types. See also :ref:`slicing `. Wildcards and strings --------------------- It is also posseble to include strings in an other string with predefined slots. The percent character(%) is used as a place-marker, followed by a single character s (%s). More about this techniques can be found in the learning station :ref:`modulo `.