0% found this document useful (0 votes)
16 views

String and MathFunc

The document provides an overview of strings and mathematical modules in Python. It discusses strings in detail, including string slicing, formatting, methods and special characters. It also reviews the math and cmath modules for common mathematical functions. Formatted output is demonstrated using both the str.format() method and newer f-strings.

Uploaded by

Salvador Modesto
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

String and MathFunc

The document provides an overview of strings and mathematical modules in Python. It discusses strings in detail, including string slicing, formatting, methods and special characters. It also reviews the math and cmath modules for common mathematical functions. Formatted output is demonstrated using both the str.format() method and newer f-strings.

Uploaded by

Salvador Modesto
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

TP 02

STRINGS, FORMATTED OUTPUT, MATH FUNCTIONS

UA.DETI.IP
Carlos Costa
Summary

 Strings
– Review
– Special characters
– Slicing
– Content check
– Modifications
– Methods
– Formatting

 Mathematical modules
– module concept
– math and cmath modules

2
Python String (review)

 A sequence of characters
>>> print("IP course 2021-22") #OK
>>> print('IP course 2021-22') #OK

– letters, numbers and >>> print('Let's go coding') #Error


symbols >>> print("Let's go coding") #OK

>>> print("She "likes" coding") #Error

 Uses quotes 'Hello' or “Hello” >>> print('She "likes" coding') #OK

>>> print("""Learn Python


Programming""") #OK
 Triple quotes – multiline string >>> print('''Learn Python
Programming''') #OK

>>> first_name = "Carlos”; last_name = "Costa"


 + for concatenation >>> full_name = first_name + " " + last_name

>>> print ('IP is cool! '*3)


 * for replication IP is cool! IP is cool! IP is cool!

>>> age = 20
>>> print (full_name + " age: " + str(age))
 Possible to convert numbers >>> 100 + int(”33”)

into strings, and vice-versa 133


>>> int(3.14) #down casting
– int(), float(), str() 3

3
Special characters
 The backslash (\) is used to introduce a special character

>>> print('Let's go coding’) #Error Escape


Meaning
>>> print("Let\'s go coding") #OK sequence

>>> print("She "likes" coding") #Error \\ Backslash


>>> print("She \"likes\" coding") #OK
\’ Single quote
>>> print("IP course - 2021\\22")
IP course - 2021\22 \” Double quote

# Introduces new line (\n) \n Newline


>>> print ("Carlos Costa,\nAveiro University")
Carlos Costa,
\t Tab
Aveiro University

# Introduces tab (\t)


>>> print("Carlos Costa,\[email protected]"); print("Susana Mota,\[email protected]")
Carlos Costa, [email protected]
Susana Mota, [email protected]
4
String – sequence of characters

 Strings are arrays of bytes representing unicode


characters

 Python does not have the character data type


– character is a string with a length of 1

 Square brackets [] used to access to string elements


>>> str1 = ('FACE')
>>> print(str1[0])
F
>>> print(str1[3])
E
>>> print(str1[-1])
E
>>> print(str1[-3])
A
5
String length

 len(…) – built-in function that returns the length of a


string
>>> s = "Aveiro city!”
>>> l = len(s)
>>> print (l)
12

 Useful to avoid errors – access to indexes beyond


string end
>>> print (S[14])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
6
String slicing

 Used to obtain sub-strings of the original string


Default values:
start - 0
stop - the last index of the string
step - 1

S = "Aveiro city!"

S[0:6] A v e i r o c i t y !

S[7:] A v e i r o c i t y !

S[-8:-6] A v e i r o c i t y !

S[0:5:2] A v e i r o c i t y !
7
* stop: end position not included
String slicing (cont)
>>> S = "Aveiro city!"
>>> S[0:6] # default step - 1
'Aveiro'
>>> S[7:] # default end position - str length
'city!'
>>> S[-8:-6] # negative start | end positions
'ro'
>>> S[0:5:2] # defined step - 2
'Aer'
>>> S[:6] # default start position - [0]
'Aveiro'
>>> S[:6:-1] # negative step – start at the end
'!ytic' # of the string and move left
>>> S[::-1] # reverse the string
'!ytic orievA'
>>> S[7:-2:] # combine positive and neg indexes
'cit'
8
Check string content

 in keyword
– check if a certain phrase or character is present in a string
– returns True or False
– can be used in a if statement (we will see later)

>>> print ('city' in S)


True
# Check if NOT
>>> print ('city' not in S)
False

9
String immutability and modifications

 Strings are immutable – cannot be modified


 Several methods for String modifications
– they return a new string object
>>> txt = "Aveiro University"
>>> txt[2] = 'E'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

>>> txt.replace("University", "Univ")


'Aveiro Univ'
>>> print(txt)
Aveiro University

>>> new_txt = txt.replace("University", "Univ")


>>> print(new_txt)
Aveiro Univ
10
String methods

 Method are function applied to a particular object

 Syntax
<object>.<method>(<parameters>)

 Examples

>>> txt = "Hello students!"


>>> txt.find('s')
6

>>> txt.upper()
'HELLO STUDENTS!'
11
String methods (cont)

 Many useful methods… Play ▶


str.isalpha() True if all characters are alphabetic.
str.isdigit() True if all characters are digits.
str.is... ...
str.upper() Convert to uppercase.
str.lower() Convert to lowercase.
... ...
str.strip() Remove leading and trailing whitespace.
str.lstrip() Remove leading whitespace.
str.rstrip() Remove trailing whitespace.
s1.find(s2) Finds string s2 in string s1
str.split() Split str by the whitespace characters.
str.split(sep) Split str using sep as the delimiter.

12
String formating

 How to get a beautiful output?


– For instance, produce the following output
"The bill value is $1.50"

 Two ways to obtain a formatted string


1. String format method: str.format()
>>> total = 1.50
>>> s = "The bill value is ${0:0.2f}".format(total))
>>> print(s)
The bill value is $1.50

2. f-strings (f”…”)
>>> s = f" The bill value is ${total:0.2f}"
>>> print (s)
The bill value is $1.50

13
str.format() method

 Allows variable substitutions and value formatting

– Format strings contain “replacement fields” surrounded by {}


– Anything that is not contained in braces is considered literal text
 Example
>>> print('{0} {1} cost ${2}'.format(6, 'bananas', 1.74))
6 bananas cost $1.74

14
str.format() method (cont)

 Using keyword arguments instead of positional parameters

 Example
>>> print('{quantity} {item} cost
${price}'.format(quantity=6, item='bananas', price=1.74))
6 bananas cost $1.74

15
str.format() method examples
>>> x, y, z = 1, 2, 3
>>> '{0}, {1}, {baz}'.format(x, y, baz=z)
'1, 2, 3’

# formatting...
>>> '{} {}'.format('one', 'two')
'one two'
>>> '{:*>10}'.format('test')
'******test'
>>> '{:04d}'.format(42)
'0042'
>>> '{:5.2f}'.format(3.2451)
' 3.25'

>>> print(1,2,3)
1 2 3
>>> print('{:4d}{:4d}{:4d}'.format(1,2,3))
1 2 3

>>> print(10,20,30)
10 20 30
>>> print('{:4d}{:4d}{:4d}'.format(10,20,30))
10 20 30

16
f-String

 New and improved way to format Strings

 Syntax similar to str.format() but less verbose


f”…”, F”…”, f’…’, F’…’

 Example
>>> name = "Sofia"
>>> age = 33
>>> f"Hello, {name}. You are {age}."
'Hello, Sofia. You are 33.'

17
Examples: Str-method versus f-String

Str-method F-String

# 'one two'
'{} {}'.format('one', 'two') f"{'one'} {'two'} "

# '******test'
'{:*>10}'.format('test’) f"{'test':*>10}”

# '0042'
'{:04d}'.format(42) f'{42:04d}'

# ' 3.25'
'{:5.2f}'.format(3.2451) f'{3.2451:5.2f}'

# 1 2 3
'{:4d}{:4d}{:4d}'.format(1,2,3) f'{1:4d}{2:4d}{3:4d}'

# 10 20 30
'{:4d}{:4d}{:4d}'.format(10,20,30) f'{10:4d}{20:4d}{30:4d}'

18
Math functions

 Python math module that provides most of the


familiar mathematical functions
– cmath module to work with complex numbers

 Python Module?
– File defining a collection of related functions and objects

 The module must be imported before using it


>>> import math
>>> import cmath

 Using a module function


<name of the module> . <name of the function>
19
Math functions – usage examples
>>> degrees = 45

>>> radians = degrees * math.pi / 180

# Angle arguments are always in radians!


>>> math.sin(radians)
0.707106781187

>>> cmath.sqrt(-1)
1j

20
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

21

You might also like