Character strings
Strings are delimited with single '
or double "
or triple-double """
inverted commas. The latter variant allows multi-line strings to be written:
Example
"Hello world"
'Hello world'
""" Hello
dear
world"""
A mixture of inverted commas for separation is not permitted, but their occurrence in a text separated by other inverted commas is:
Example
"Can't touch this"
'Then he said "Heureka!".'
However, if both characters '
and "
are to occur, then the occurrences of the outer inverted commas in the string itself must be masked by prefixing them with \
:
Example
'Then he said "Can\'t touch this".'
Two strings can be combined:
Example
"Whoever says A " + "can be wrong." # "Whoever says A can be wrong."
With a defined addition, a multiplication is of course also defined:
Example
"Na" * 12 + " Batman!" # 'NaNaNaNaNaNaNaNaNaNaNaNa Batman!'
If you have a list of strings, you can join them using the str.join function:
Example
",".join(["Monday", "Tuesday"]) # 'Monday,Tuesday'
"-...-".join(["Monday", "Tuesday", "Wednesday"]) # 'Monday-...-Tuesday-...-Wednesday'
Parts of a string can be obtained via the indexing [a:b]
. Here, a
is the first character to be extracted and b
is the first character that should no longer be included. In Python, the count starts at 0.
Example
"Testator"[2:6] # 'stat'
Individual letters can also be extracted in this way, negative indices count from the back:
Example
"Part"[0] # 'P'
"Part"[-1] # 't'
"Part"[-3:-1] # 'ar'
If one of the limits in [a:b]
is omitted, 0 is assumed for a
and -1 for b
. This is a general convention in Python beyond strings.
Example
"Part"[1:] # 'art'
"Part"[-1] # 't'
"Part"[:-2] # 'Pa'
Conversion
Conversion is simple but not always obvious:
Example
str(2) # '2'
str(1/9*9) # '1.0', because 1/9 was evaluated as a decimal number
str(1) # '1'
str(1/9) # '0.1111111111111111'