Abbreviations and more types of literals in Python
(Part of the content of this lesson [raw and formatting string literals] was partly covered in a preceding lesson.)
Raw literals
A raw string literal starts with an »r«. In such a literal, most occurences backslashes denote a backslash, but it may not end with a backslash (in front of the terminating quote).
- Console transcript
print( "\\a" )
\a
print( r"\\a" )
\\a
print( r"\a" )
\a
print( r"a\" )
File "<stdin>", line 1
print( r"a\" )
^
SyntaxError: EOL while scanning string literal
Formatting literals
A formatting string literal starts with an »f«. In such a literal, text in braces is evaluated, formatted and then inserted instead of the text in braces.
- “Braces” are called “curly brackets” in British English.
- Evaluation
f'abc'
'abc'
- Evaluation
f'abc{ 1 + 1 }'
'abc2'
- Evaluation
f'abc{1+1}'
'abc2'
An equals sign »=« will also insert the expression used.
- Evaluation
f'abc{1+1=}'
'abc1+1=2'
- Evaluation
f'abc{ 1 + 1 = }'
'abc 1 + 1 = 2'
An equals sign »=« will also insert the expression used.
».3f« demands the formatting of a floating-point number with a precision of three (three digits after the decimal-point character).
- Console transcript
from math import pi
f'{pi}'
'3.141592653589793'
- Console transcript
from math import pi
f'{pi:.3f}'
'3.142'
- Console transcript
from math import pi
f'{pi=:.3f}'
'pi=3.142'
»x« requests formating in the hexadecimal number system.
- Console transcript
from math import pi
f'{20:x}'
'14'
One can specify a field with a width and an alignment.
- Console transcript
f'{"abcdef":<10}'
'abcdef '
- Console transcript
f'{"abcdef":>10}'
' abcdef'
- Console transcript
f'{"abcdef":10}'
'abcdef '
In case of a string, the precision gives the maximum length.
- Console transcript
f'{"abcdef":.3}'
'abc'
A field width can be combined with a precision.
- Console transcript
f'{"abcdef":10.3}'
'abc '
Sources
- Source
The Python Language Reference, Release 3.8.0a0, section 2.4.3 Formatted string literals
Multiline string literals in Python
Literals beginning with »'''«
Literals beginning and ending with »'''« may contain »'«, »''« (but not »'''«) and literal line endings.
- Console transcript
print( '''Alpha'
Gamma''Epsilon
Zeta''' )Alpha'
Gamma''Epsilon
Zetaprint( repr( '''Alpha'
Gamma''Epsilon
Zeta''' ))"Alpha'\nGamma''Epsilon\nZeta"
print( "Alpha'\nGamma''Epsilon\nZeta" )
Alpha'
Gamma''Epsilon
Zeta
»"""« can be used as well.
- Console transcript
print( """Alpha"
Gamma""Epsilon
Zeta""" )Alpha"
Gamma""Epsilon
Zeta
If ever needed, strings with sequences of consecutive apostrophes and quotation marks can be obtained by addings strings. This is rarely needed.
- Konsoleninteraktion
print( "'''''''''" + '""""""""' )
'''''''''""""""""
This can even be written, confusingly, as follows.
- Konsoleninteraktion
print( "'''''''''"'""""""""' )
'''''''''""""""""
Abbreviations used in connection with attributes
Remember that the entries of a module are attributes of that module.
- Notations for attribute accesses
import math
getattr( math, "floor" )( 2.2 )
math.floor( 2.2 )
So, »A.B « is an abbreviation for »getattr( A, "B " )«.
Literals for tuples
A comma connects expressions into a tuple.
- Notations for tuples
1, 2
Often parentheses are used, but the comma is the crucial point.
- Notations for tuples
( 1, 2 )
- multil-ine Notation for tuples
( 1,
2 )
However, an empty list is given by an empty pair of parens.
- Notations for tuples
()
An tuple with on component requires parens and a comma.
- Notations for tuples
( 1, )
Contents can be mixed-type.
- Notations for tuples
( False, 2, "z", () )
Multiplication is akin to multiplication of strings.
- Notations for tuples
( 1, 2 )* 3
Effects happen in the sequence given.
- Notations for tuples
print( "a" ), print( "b" )
Some examples.
- Examples using tuple notation
tuple( map( lambda x: 2*x, ( 3, 'b', ( 'x', 'y' ))))
(6, 'bb', ('x', 'y', 'x', 'y'))
- Examples using tuple notation
tuple( zip( ( 'a', 'b', 'c' ), ( 1, 2 )))
(('a', 1), ('b', 2))
- Examples using tuple notation
import functools
functools.reduce( lambda x, y: x+y, ( 'a', 'b', 'c' ))
'abc'
How would you make the Python implementation print out how many ›Trues‹ are in the expression below?
- A tuple
( True, True, False, True, False, False, True, False, False, True, True, True, False, True, False, False, True, False, False, True )
“Note that tuples are not formed by the parentheses, but rather by use of the comma operator. The exception is the empty tuple, for which parentheses are required — allowing unparenthesized “nothing” in expressions would cause ambiguities and allow common typos to pass uncaught.” – The Python Language Reference (2020)
Literals for list
The names were chosen somewhat unluckily, because both tuples and lists are lists in the colloquial sense of the word “list ”.
So, whenever you want a “list”, use a tuple. Use a list proper only if you need the mutability.
This is the difference between lists and tuples: A list can be modified.
Lists are mutable, tuples are not.
Modification is error-prone and should be avoided. So prefer tuples.
For lists use the tuple notation with parentheses, but this time use brackets instead of parentheses.
- Notations for list
[]
[ 1 ]
[ 1, 2 ]
[ False, 2, "z" ]
[ print( "a" ), print( "b" )]
[ 1, "z" ]* 2
We'll see later how list can actually be modified!
Abbreviations used in connection with items
Remember that some objects have items in addition to attributes. Item access can be abbreviated using a postponed pair of brackets.
- Notations for item accesses
import operator
operator.getitem( "abc", 1 )
'b'
"abc"[ 1 ]
'b'
So, brackets can be used to write lists and to write items. Their respective meaning depends on their position.
- Notations for item accesses
[ 1, 2, 3, 4 ][ 2 ]
3
Abbreviations used in connection with slices
Comparisons
Tuples can be compared structurally, that is similar to strings.
- Notations for tuples
print( "a" ), print( "b" )
( 1, 2 )==( 1, 3 )
( 1, 2 )<( 1, 3 )
- Examples using tuple notation
tuple( filter( lambda x: type( x )== str, ( 'a', 1, 'b', (), 'c', () )))
('a', 'b', 'c')
Assignments
Monkey patching
The modification of modules just shown is also known as “monkey patching”. Modules can be modified for a whole session (usually used only as a last ressort).
- Monkey patching »math«
from math import pi
pi = 3
print( pi )
from math import pi
print( pi )
import math
math.pi = 3
print( math.pi )
from math import pi
print( pi )
import math
print( math.pi )
The alias effect
We now can explore some effects in a way that is more transparent than when using a »getattr«, for example, the alias effect.
- The alias effect
x = lambda: None
y = x
x.a = 20
print( y.a )
We have changed »x.a«, yet »y.a« changed!
This is because »x« and »y« refer to the same object.
We can prevent this creating a copy, which is the purpose of the three lines beginning »import functools«.
- Prevention of the alias effect
x = lambda: None
import functools
y = functools.partial( x )
y.__dict__.update( x.__dict__ )y.a = 30
print( x.a )
An attribute access can also be used to the left of an equals sign.
- Notations for attribute accesses
import math
setattr( math, "pi", 3 )
getattr( math, "pi" )
- Notations for attribute accesses
math.pi = 4
print( math.pi )
So, »A.B =x « is an abbreviation for »setattr( A, "B ", x )«.
By deconstruction several names can be assigned using only one assignment operator.
- Notations for tuples
x, y = 1, 2
x = 1, 2
a, b = x
b, a = a, b
- lists
list_ =[ 1, 2, 3 ]
operator.setitem( list_, 1, 5 )
print( list_ )
[1, 5, 3]
An item access can also be used to the left of an equals sign.
- Notations for item accesses
list_[ 1 ]= -2
print( list_ )
[1, -2, 3]