Codementor Events

Python: party with Strings

Published May 20, 2018Last updated Nov 16, 2018
Python: party with Strings

Since Python 3.6 a new way to handle strings has become available. Suppose you have variables:
name = "andy"
age = 42
likes = "Python"

and you want to generate a string that says:
"We know someone called andy who is aged 42 and likes to use Python to program."
It's now simple and elegant to do that using F-Strings.

Here's how it works:
print(f"We know someone called {name} who is aged {age} and likes to use {likes} to program.")
That's it. No type conversion, concatenation, etc. Just start the string with f before the first ", and enclose all variables in {}.

It works anywhere you need to process a string. Give it a try!

Discover and read more posts from Andy Miles
get started
post commentsBe the first to share your opinion
Ann
6 years ago

Lol the pic cracks me and is a perfect choice on the topic. Thank you for the info!

Andy Miles
6 years ago

Good question - print(f"My name is {name}") looks really elegant to me, it doesn’t need the $ and there is a precedent for “qualifying” strings with a preceding character like this across other languages, albeit in other usage situations.

Zach Welz
6 years ago

Pretty sure it is recommended to call them all at the end explicitly using the standard lib string format method.

print("We know someone called {} who is aged {} and likes to use {} to program.".format(name, age, likes))
Andy Miles
6 years ago

Actually this is the former way to do it before f-strings. The code works as stated. Give it a try in iPython!

Dennis G Daniels
6 years ago
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "name = \"andy\"\n",
    "age = 42\n",
    "likes = \"Python\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "We know someone called andy who is aged 42 and likes to use Python to program.\n"
     ]
    }
   ],
   "source": [
    "print(f\"We know someone called {name} who is aged {age} and likes to use {likes} to program.\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
Dennis G Daniels
6 years ago

I did exactly what you recommended… I tried the code in Ipython/jupyter and it worked like a dream. Thanks.

Andy Miles
6 years ago

That’s great to hear! f-strings are very powerful. Great to use in the logging module too.

Show more replies