Strings Math
Strings Math
TP 02
S TRINGS , F ORMATTED O UTPUT, M ATH F UNCTIONS
B a s e a d o n o s M a te r i a i s d e F u n d a m e n to s d e P ro g ra m a ç ã o d e
J o ã o M a n u e l Ro d r i g u e s
António J. R. Neves
1
Topics
• Strings
• Formatted output
• Basic functions from library
• Modules math, cmath
2
Strings (1)
• Strings are sequences of characters.
• String literals are delimited by single or double quotes.
fruit = 'orange'
3
Strings (2)
4
String methods
5
String Formatting: str.format()
print(1,2,3) #-> 1 2 3
print(10,20,30) #-> 10 20 30
print('{:4d}{:4d}{:4d}'.format(1,2,3)) #-> 1 2 3
print('{:4d}{:4d}{:4d}'.format(10,20,30)) #-> 10 20 30
6
String Formatting: f-strings
The latest versions of Python include f-strings (f”…”)
allowing formatting strings in place. The string starts with f.
• Format strings contain “replacement fields” surrounded by {}.
• Anything that is not contained in braces is considered literal text.
f"{'one'} {'two'}" #-> 'one two'
f"{'test':*>10}" #-> '******test'
f'{42:04d}' #-> '0042'
f'{3.2451:5.2f}' #-> ' 3.25'
print(1,2,3) #-> 1 2 3
print(10,20,30) #-> 10 20 30
print(f'{1:4d}{2:4d}{3:4d}') #-> 1 2 3
print(f'{10:4d}{20:4d}{30:4d}') #-> 10 20 30
7
Math functions
• Python has a math module that provides most of the
familiar mathematical functions. Exist an equivalent cmath
module to work with complex numbers.
• A module is a Python file that defines a collection of
related functions and objects.
• Before using a module, it should be imported:
>>> import math
>>> import cmath
• To access one of the functions, specify the name of the
module and the name of the function, separated by a dot.
>>> degrees = 45
>>> radians = degrees / 360.0 * 2 * math.pi
>>> math.sin(radians)
0.707106781187 # Angle arguments are always in radians!
>>> cmath.sqrt(-1)
1j
8
Some math functions
math. Description
pi An approximation of pi.
e An approximation of e.
sqrt(x) The square root of x.
sin(x) The sine of x.
cos(x) The cosine of x.
tan(x) The tangent of x.
asin(x) The inverse of sine x.
acos(x) The inverse of cosine x.
atan(x) The inverse of tangent x.
log(x) The natural (base e) logarithm of x.
log10(x) The common (base 10) logarithm of x.
exp(x) The exponential of x.
ceil(x) The smallest whole number>= x.
floor(x) The largest whole number <= x.
degrees(x) Convert angle x from radians to degrees.
radians(x) Convert angle x from degrees to radians.
help(math) Shows all math functions in the console