|Every programming language is using strings as a data type. The Python way to handle strings, is shown in this station.|
Save the following text, line by line into variables:
"Shall I compare thee to a summer's day? Thou art more lovely and more temperate..." Lines from Shakespeare's Sonnet 18.
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:
Each variable get's own value.
a = "A soup" b = "can" c = "you?" print(a, b, c)
Building longer Strings from substrings, is an technique used often.
b = "can" a = "A soup" c = "you?" d = a + " " + b + " " + b + " " + b + "-" + b + ";" d = d + " " + b + " " + c + "\n" print(d)
|Hint:||The same result can be achieved with other data types like tuple and list.|
Extract parts of string
This task is possible with the slicing operator. This operation is available for all sequence data types. See slicing.
Wildcards and strings
It is also posseble to include strings in 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 modulo.