f’You! You {effing} f-string!’
If you came here for some hate on f-strings, you went to the wrong place. I love f-strings. Print statements are useful for building functions and seeing where we are in any given process in python. Formatted string literals, or f-strings, have the benefits of speed, simple syntax, and the ability to utilize arbitrary expressions.
Simple syntax:
hero_name = ‘Superman’
secret_identity = ‘Clark Kent’
paramour_name = ‘Lois Lane’
f’Does {paramour_name} know {secret_identity} is {hero_name}?’'Does Lois Lane know Clark Kent is Superman?'
Pretty cool, right? Clean and simple.
Arbitrary expressions:
Some examples from class today.
embedding_vector_length = 32
model = Sequential()
model.add(Embedding(top_words, embedding_vector_length, input_length=max_review_length))
model.add(LSTM(100))
model.add(Dense(1, activation=’sigmoid’))
model.compile(loss=’binary_crossentropy’, optimizer=’adam’, metrics=[‘acc’])
f’{model.summary()}’
model.fit(X_train, y_train, validation_data=[X_test, y_test], epochs=1, batch_size=64)
Because the model.summary() is printed before the neural net is fitted, you can examine the summary while you wait!
scores = model.evaluate(X_test, y_test, verbose=2)
f’Accuracy score is {round(scores[1]*100)}’'Accuracy score is 83.0'
Awesome, right? Calling those functions in the middle of a block of code was easy as heck.
Speed:
Time the performance of our print statement 10,000 times with a .format method.
import timeit
timeit.timeit(“””hero_name = ‘The Flash’
secret_identity = ‘Wally West’
paramour_name = ‘Iris West’
‘Does {} know {} is {}?’.format(paramour_name, secret_identity, hero_name)”””, number = 10_000)0.007361477008089423
Time the performance of our print statement 10,000 times with an f-string.
import timeit
timeit.timeit(“””hero_name = ‘The Flash’
secret_identity = ‘Wally West’
paramour_name = ‘Iris West’
f’Does {paramour_name} know {secret_identity} is {hero_name}?’”””, number = 10_000)0.00228431005962193
The Fastest Man Alive has nothing on our f-strings.
Next time you want to use a print statement or, shudder, a .format method; consider using f-strings. They’re fast, easy, and can handle some complex expressions. Now go build some effing f-strings!