Skip to content

Instantly share code, notes, and snippets.

@LouisdeBruijn
Last active January 1, 2021 15:10
Show Gist options
  • Select an option

  • Save LouisdeBruijn/a9518be4ceec3309b3cf01585ee732b2 to your computer and use it in GitHub Desktop.

Select an option

Save LouisdeBruijn/a9518be4ceec3309b3cf01585ee732b2 to your computer and use it in GitHub Desktop.
purpose = "string formatting"
percent_sign = "% operator"
dot_format_method = ".format() method"
string_literal = "f-string"
quantity, revenue = 100, 25
d = {"costs": 300}
list_operations = ['slicing and other things', 'indexing', 'key references']
limitations = ["be empty", "contain comments", "contain backslashes"]
print("Before w used the %s for %s." % (percent_sign, purpose))
>>> "Before w used the % operator for string formatting."
print("Since Python 2.7 we are using the {method} for {0}, enabling us {1:^8s}.".format(purpose, "to do fun things", method=dot_format_method))
>>> "Since Python 2.7 we are using the .format() method for string formatting, enabling us to do fun things."
print(f"But now with Python 3.6 come the {string_literal}!")
>>> "But now with Python 3.6 come the f-string!"
print(f"With f-strings we can do arithmetic expressions: price €{quantity / revenue} per unit.")
>>> "With f-strings we can do arithmetic expressions: price €4.0 per unit."
print(f"We can do {list_operations[0][0:7]}, {list_operations[1]} and {list_operations[2]}: cost €{d['costs'] / quantity} per unit.")
>>> "We can do slicing, indexing and key references: cost €3.0 per unit."
print(f"f-strings have three limitations: {*limitations,}.")
>>> "f-strings have three limitations: ('be empty', 'contain comments', 'contain backslashes')."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment