{ "cells": [ { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "# How to convert ordinary string to an f-string or evaluate an ordinary string as an f-string?\n", "\n", "At this month's COhPy meeting,\n", "someone asked how to either\n", "convert an ordinary string to an f-string\n", "or evaluate an ordinary string as an f-string.\n", "\n", "One solution is to use eval() as shown below.\n", "What other solutions are there?\n", "\n", "Why was %r used instead of %s or %a in the first eval expression?" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false, "deletable": true, "editable": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "iso:\n", "2017-03-27\n", "2017-04-24\n", "2017-05-22\n", "us:\n", "3/27/2017\n", "4/24/2017\n", "5/22/2017\n", "other:\n", "27 3 2017\n", "24 4 2017\n", "22 5 2017\n" ] } ], "source": [ "date_formats = {\n", " 'iso': '{year}-{month:02d}-{day:02d}',\n", " 'us': '{month}/{day}/{year}',\n", " 'other': '{day} {month} {year}',\n", "}\n", "dates = (\n", " (2017, 3, 27),\n", " (2017, 4, 24),\n", " (2017, 5, 22),\n", ")\n", "\n", "for format_name, format in date_formats.items():\n", " print(f'{format_name}:')\n", " for year, month, day in dates:\n", " print(eval('f%r' % format))" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "One surprise for me is that this is another way of deferring\n", "evaluation of f-strings, and that it is easier to read than\n", "using lambdas. I wonder how much slower eval() is than using\n", "the lambdas." ] }, { "cell_type": "markdown", "metadata": { "collapsed": false, "deletable": true, "editable": true }, "source": [ "Which of the following is easier for you read?\n", "Why/how?\n", "\n", " print(eval('f%r' % format))\n", " print(eval(f'f{format!r}'))" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "I wonder what sympy thinks of manipulating f-strings." ] } ], "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.0" } }, "nbformat": 4, "nbformat_minor": 2 }