The f means Formatted string literals and it's new in Python 3.6.
A formatted string literal or f-string is a string literal that is prefixed with
forF. These strings may contain replacement fields, which are expressions delimited by curly braces{}. While other string literals always have a constant value, formatted strings are really expressions evaluated at run time.
Some examples of formatted string literals:
>>> name = "Fred"
>>> f"He said his name is {name}."
"He said his name is Fred."
>>> name = "Fred"
>>> f"He said his name is {name!r}."
"He said his name is Fred."
>>> f"He said his name is {repr(name)}." # repr() is equivalent to !r
"He said his name is Fred."
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}" # nested fields
result: 12.35
>>> today = datetime(year=2023, month=1, day=27)
>>> f"{today:%B %d, %Y}" # using date format specifier
January 27, 2023
>>> number = 1024
>>> f"{number:#0x}" # using integer format specifier
0x400
Answer from Pedro Lobito on Stack OverflowSo how does Print function work in Python?
python - What is print(f"...") - Stack Overflow
Printing a function in Python - Stack Overflow
Python - print function output - Stack Overflow
So I am a beginner who was learning python and the first thing I learnt was printing strings. Then later on I learnt about functions and it's only now I realised that print itself is a function. Like when we say print ('hello world') we are basically calling an already existing function and not doing anything new. I didn't realise it till now. But the question I got is what does this original print function contain? How does it work? Is it possible for me to built it from scratch by myself?
The f means Formatted string literals and it's new in Python 3.6.
A formatted string literal or f-string is a string literal that is prefixed with
forF. These strings may contain replacement fields, which are expressions delimited by curly braces{}. While other string literals always have a constant value, formatted strings are really expressions evaluated at run time.
Some examples of formatted string literals:
>>> name = "Fred"
>>> f"He said his name is {name}."
"He said his name is Fred."
>>> name = "Fred"
>>> f"He said his name is {name!r}."
"He said his name is Fred."
>>> f"He said his name is {repr(name)}." # repr() is equivalent to !r
"He said his name is Fred."
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}" # nested fields
result: 12.35
>>> today = datetime(year=2023, month=1, day=27)
>>> f"{today:%B %d, %Y}" # using date format specifier
January 27, 2023
>>> number = 1024
>>> f"{number:#0x}" # using integer format specifier
0x400
In Python 3.6, the f-string, formatted string literal, was introduced(PEP 498). In short, it is a way to format your string that is more readable and fast.
Example:
agent_name = 'James Bond'
kill_count = 9
# old ways
print("%s has killed %d enemies" % (agent_name,kill_count))
print('{} has killed {} enemies'.format(agent_name,kill_count))
print('{name} has killed {kill} enemies'.format(name=agent_name,kill=kill_count))
# f-strings way
print(f'{agent_name} has killed {kill_count} enemies')
The f or F in front of strings tell Python to look at the values , expressions or instance inside {} and substitute them with the variables values or results if exists. The best thing about f-formatting is that you can do cool stuff in {}, e.g. {kill_count * 100}.
You can use it to debug using print e.g.
print(f'the {agent_name=}.')
# the agent_name='James Bond'
Formatting, such as zero-padding, float and percentage rounding is made easier:
print(f'{agent_name} shoot with {9/11 : .2f} or {9/11: .1%} accuracy')
# James Bond shoot with 0.82 or 81.8% accuracy
Even cooler is the ability to nest and format. Example date
from datetime import datetime
lookup = {
'1': 'st',
'21': 'st',
'31': 'st',
'2': 'nd',
'22': 'nd',
'3': 'rd',
'23': 'rd'
}
dato = datetime.now()
print(f"{dato: %B %-d{lookup.get(f'{dato:%-d}', 'th')} %Y}")
# April 23rd 2022
Pretty formatting is also easier
tax = 1234
print(f'{tax:,}') # separate 1k \w comma
# 1,234
print(f'{tax:,.2f}') # all two decimals
# 1,234.00
print(f'{tax:~>8}') # pad left with ~ to fill eight characters or < other direction
# ~~~~1234
print(f'{tax:~^20}') # centre and pad
# ~~~~~~~~1234~~~~~~~~
The __format__ allows you to funk with this feature. Example
class Money:
def __init__(self, value, currency='โฌ'):
self.currency = currency
self.value = value
def __repr__(self):
return f'Money(value={self.value}, currency={self.currency})'
def __format__(self, *_):
return f"{self.currency}{float(self.value):.2f}"
tax = 12.3446
money = Money(tax, currency='$')
print(f'{money}')
# $12.34
print(money)
# Money(value=12.3446, currency=$)
There is much more. Readings:
- PEP 498 Literal String Interpolation
- Python String Formatting
This is not the answer you are looking forโฆ
But in interest of completeness, suppose you did want to print the code of the function itself. This will only work if the code was executed from a file (not a REPL).
import inspect
code, line_no = inspect.getsourcelines(two)
print(''.join(code))
That said, there aren't many good reasons for doing this.
Your functions already print text, you don't need to print the functions. Just call them (don't forget parenthesis).
def one():
print ("lol")
print ("dood")
def two():
one()
one()
two()