Your first Python program
Programmers take their first steps with the famous “Hello, World!” program, one which prints the appropriate string. Python supports several data types, and strings are one such.
But humans don’t think or speak in “strings!“ so Python introduced f”-strings” which feature logical properties such as those encountered in human speech.
Open up your IPython REPL and follow along.
> "hello world"
'hello world'
Our failure is immediately obvious. The human thought is simply two words, “hello” and ” world” but the English language representation is (canonically) “Hello, World!”.
We must tell the programming language what to do, and we do that with functions, but normal strings do not have functions. And so representing cognitive English in Python was impossible until 2016.
f-strings
functional strings allow us to manipulate strings from within, putting Python inside the string, so we can have strings that represent themselves like we expect
we take our humble hello world and make it into a function
> ("hello world")
> f"{(lambda x: x)("hello world")}"
And then we operate on it
> f"{(lambda x: ", ".join(x.title().split()) + "!")("hello world")}"
But humans may say hello to many things. Not just the world!
> f"{(lambda x: ", ".join(x.title().split()) + "!")(f"{(lambda x: f"hello {x}")("friend")}")}"
'Hello, Friend!'
Naturally we might want to format our expressions, which is as simple
as nesting them. To center our text in a beautiful nest, we may. Start
with an extra f
. One advantage of working inside strings
is we can easily break up long lines:
> f"{(lambda x: f"{", ".join(x.title().split()) + "!":{f"*^{3/5*len(x)**1.5}"}}")
> (f"{(lambda x: f"hello {x}")("friend")}")}"
'*****Hello, Friend!*****'
We have functionalized our string, and can say hello to all of our friends!
Let's create a list comprehension with all of our greetings! (code)
> x = ['geryon', 'anataeus', 'dispater', 'ereshkigal']
> [f"{(lambda x: f"{", ".join(x.title().split()) +
> "!":{f"*^{3/5*len(x)**1.5}"}}")(f"{(lambda x: f"hello {x}")(x)}")}" for x in x]
['*****Hello, Geryon!*****',
'*******Hello, Anataeus!********',
'*******Hello, Dispater!********',
'*****************Hell*****************']