Sformatowany literał łańcuchowy

Wyrażenia regularne w Pythonie

Maria Eugenia Inzaugarat

Data Scientist

f-stringi

  • Minimalna składnia
  • Dodaj prefiks f do łańcucha

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
Wyrażenia regularne w Pythonie

Konwersja typów

  • Dozwolone konwersje:
    • !s (reprezentacja łańcuchowa)
    • !r (łańcuch z reprezentacją do wydruku, tj. z cudzysłowami)
    • !a (jak !r, ale znaki spoza ASCII są kodowane)

 

name = "Python"

print(f"Python is called {name!r} due to a comedy series")
Python is called 'Python' due to a comedy series
Wyrażenia regularne w Pythonie

Specyfikatory formatu

  • Standardowe specyfikatory formatu:
    • e (notacja naukowa, np. 5 10^3)
    • d (liczba całkowita, np. 4)
    • f (liczba zmiennoprzecinkowa, np. 4.5353)

 

number = 90.41890417471841

print(f"In the last 2 years, {number:.2f}% of the data was produced worldwide!")
In the last 2 years, 90.42% of the data was produced worldwide!
Wyrażenia regularne w Pythonie

Specyfikatory formatu

 

  • datetime

 

from datetime import datetime
my_today = datetime.now()
print(f"Today's date is {my_today:%B %d, %Y}")
Today's date is April 14, 2019
Wyrażenia regularne w Pythonie

Wyszukiwanie indeksów

family = {"dad": "John", "siblings": "Peter"}
print("Is your dad called {family[dad]}?".format(family=family))
Is your dad called John?

 

  • Używaj cudzysłowów przy wyszukiwaniu indeksów: family["dad"]
print(f"Is your dad called {family[dad]}?")
NameError: name 'dad' is not defined
Wyrażenia regularne w Pythonie

Sekwencje ucieczki

  • Sekwencje ucieczki: ukośniki wsteczne \
print("My dad is called "John"")
SyntaxError: invalid syntax

 

my_string = "My dad is called \"John\""
My dad is called "John"
Wyrażenia regularne w Pythonie

Sekwencje ucieczki

family = {"dad": "John", "siblings": "Peter"}
  • Ukośniki wsteczne są niedozwolone w f-stringach
print(f"Is your dad called {family[\"dad\"]}?")
SyntaxError: f-string expression part cannot include a backslash

 

print(f"Is your dad called {family['dad']}?")
Is your dad called John?
Wyrażenia regularne w Pythonie

Operacje w miejscu

  • Zaleta: obliczanie wyrażeń i wywoływanie funkcji w miejscu
my_number = 4
my_multiplier = 7
print(f'{my_number} multiplied by {my_multiplier} is {my_number * my_multiplier}')
4 multiplied by 7 is 28
Wyrażenia regularne w Pythonie

Wywoływanie funkcji

def my_function(a, b):
  return a + b
print(f"If you sum up 10 and 20 the result is {my_function(10, 20)}")
If you sum up 10 and 20 the result is 30
Wyrażenia regularne w Pythonie

Czas na ćwiczenia!

Wyrażenia regularne w Pythonie

Preparing Video For Download...