Chapter2-Formatting Strings PDF
Chapter2-Formatting Strings PDF
formatting
REGULAR EXPRESSIONS IN PYTHON
Usage:
Title in a graph
Template method
str.format()
print(my_string.format(method, condition))
print("{} has a friend called {} and a sister called {}".format("Betty", "Linda", "Daisy"))
print("{2} has a friend called {0} and a sister called {1}".format("Betty", "Linda", "Daisy"))
tool="Unsupervised algorithms"
goal="patterns"
print("{title} try to find {aim} in the dataset".format(title=tool, aim=goal))
way = "code"
method = "learning Python faster"
print(f"Practicing how to {way} is the best method for {method}")
Practicing how to code is the best method for learning Python faster
name = "Python"
print(f"Python is called {name!r} due to a comedy series")
d (digit, e.g. 4)
number = 90.41890417471841
print(f"In the last 2 years, {number:.2f}% of the data was produced worldwide!")
datetime
my_number = 4
my_multiplier = 7
4 multiplied by 7 is 28
'Data science has been called sexiest job of the 21st century'
Use variables
'Data science has been called sexiest job of the 21st century'
my_string = Template('I find Python very ${noun}ing but my sister has lost $noun')
my_string.substitute(noun="interest")
'I find Python very interesting but my sister has lost interest'
my_string = Template('I paid for the Python course only $$ $price, amazing!')
my_string.substitute(price="12.50")
favorite = dict(flavor="chocolate")
my_string = Template('I love $flavor $cake very much')
my_string.substitute(favorite)
try:
my_string.substitute(favorite)
except KeyError:
print("missing information")
missing information
favorite = dict(flavor="chocolate")
my_string = Template('I love $flavor $cake very much')
my_string.safe_substitute(favorite)
f-strings:
Always advisable above all methods.
Template strings:
When working with external or user-provided strings