fstring.ipynb 22.4 KB
Newer Older
Jon Shadforth's avatar
Jon Shadforth committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
{
 "nbformat": 4,
 "nbformat_minor": 2,
 "metadata": {
  "language_info": {
   "name": "python",
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "version": "3.8.0-final"
  },
  "orig_nbformat": 2,
  "file_extension": ".py",
  "mimetype": "text/x-python",
  "name": "python",
  "npconvert_exporter": "python",
  "pygments_lexer": "ipython3",
  "version": 3,
  "kernelspec": {
   "name": "python38064bitbc551774f43d49c287181293c63f83ce",
   "display_name": "Python 3.8.0 64-bit"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# f-strings\n",
    "\n",
    "## Introduction\n",
    "\n",
    "Python offers several techniques for formatting strings, none of which are particularly elegent. \n",
    "[pep-0498](https://www.python.org/dev/peps/pep-0498) proposed _string interpolation_ as a new solution, and it's awesome! (It's very similar to (C# string interpolation)[https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated].\n",
    "\n",
    "This notebook will try to cover all of the common string formatting operations. Information and examples borrowed from:\n",
    "* https://pyformat.info\n",
    "* https://www.python.org/dev/peps/pep-0498\n",
    "* https://docs.python.org/3/library/string.html\n",
    "* https://realpython.com/python-f-strings/"
   ]
  },
  {
   "cell_type": "markdown",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "### Comparison of formatting techniques\n",
    "\n",
    "_Or, why f-string is so cool!_"
   ]
  },
  {
   "cell_type": "code",
Jon Shadforth's avatar
Jon Shadforth committed
59
   "execution_count": 7,
Jon Shadforth's avatar
Jon Shadforth committed
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": "Using .format           Popeye is 21 years old\nUsing %                 Popeye is 21 years old\nUsing string.Template   Popeye is 21 years old\nf-string                Popeye is 21 years old\n"
    }
   ],
   "source": [
    "from string import Template\n",
    "s = Template('$name is $age years old')\n",
    "name = 'Popeye'\n",
    "age = 21\n",
    "\n",
    "print('Using .format           {0} is {1} years old'.format(name, age))\n",
    "print('Using %%                 %s is %d years old' % (name,age))\n",
    "print('Using string.Template   ' + s.substitute(name=name, age=age))\n",
    "\n",
    "# f-string, or string interpolation, the best way...\n",
    "print(f'f-string                {name} is {age} years old')"
   ]
  },
  {
   "cell_type": "markdown",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "The expressions in braces can contain more than just variables. For example:"
   ]
  },
  {
   "cell_type": "code",
Jon Shadforth's avatar
Jon Shadforth committed
93
   "execution_count": 8,
Jon Shadforth's avatar
Jon Shadforth committed
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": "Next year, POPEYE will be 22 years old\n"
    }
   ],
   "source": [
    "name = 'Popeye'\n",
    "print(f'Next year, {name.upper()} will be {age + 1} years old')"
   ]
  },
  {
   "cell_type": "markdown",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "The key to understanding f-strings is that the code uses the equivalent of:\n",
    "\n",
    "`type(value).__format__(value, format_spec)`, or `format(value, format_spec)`\n",
    "\n",
    "See [PEP-498](https://www.python.org/dev/peps/pep-0498/#id26) for more details. Examples:\n"
   ]
  },
  {
   "cell_type": "code",
Jon Shadforth's avatar
Jon Shadforth committed
122
   "execution_count": 9,
Jon Shadforth's avatar
Jon Shadforth committed
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": "Today it is Thursday\nToday it is Thursday\nToday is is Thursday\n"
    }
   ],
   "source": [
    "import datetime\n",
    "now = datetime.datetime.now()\n",
    "\n",
    "# Note: datetime.__format__ is the same as datetime.strftime\n",
    "print(now.__format__('Today it is %A'))\n",
    "print(now.strftime('Today it is %A'))\n",
    "print(f'Today is is {now:%A}')"
   ]
  },
  {
   "cell_type": "markdown",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "### Basic use"
   ]
  },
  {
   "cell_type": "code",
Jon Shadforth's avatar
Jon Shadforth committed
152
   "execution_count": 10,
Jon Shadforth's avatar
Jon Shadforth committed
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": "🤓 Using f\n🤓 Using F\n🤓 Using ' allows \"double-quoted\" text\n🤓 Using \" allows 'single-quoted' text\n🤓 And triple quoted allows me to use \"double\" and 'single' quoted text without escape chars!\n🤓 Use {double braces} like this\n"
    }
   ],
   "source": [
    "emoji = '🤓'\n",
    "print(f'{emoji} Using f')\n",
    "print(F'{emoji} Using F')\n",
    "print(f'{emoji} Using \\' allows \"double-quoted\" text')\n",
    "print(f\"{emoji} Using \\\" allows 'single-quoted' text\")\n",
    "print(f\"\"\"{emoji} And triple quoted allows me to use \"double\" and 'single' quoted text without escape chars!\"\"\")\n",
    "print(f'{emoji} Use {{double braces}} like this')"
   ]
  },
  {
   "cell_type": "markdown",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "### Some bits to look out for"
   ]
  },
  {
   "cell_type": "code",
Jon Shadforth's avatar
Jon Shadforth committed
182
   "execution_count": 11,
Jon Shadforth's avatar
Jon Shadforth committed
183 184 185 186 187 188 189 190 191 192 193 194 195 196
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": "A backslash in a literal portion is...\n...ok! So is the comment characeter # \n"
    }
   ],
   "source": [
    "print(f'A backslash in a literal portion is...\\n...ok! So is the comment characeter # ')"
   ]
  },
  {
   "cell_type": "code",
Jon Shadforth's avatar
Jon Shadforth committed
197
   "execution_count": 12,
Jon Shadforth's avatar
Jon Shadforth committed
198 199 200 201 202 203 204 205 206
   "metadata": {},
   "outputs": [],
   "source": [
    "# Enable next line to test...\n",
    "# print(f'But in an expression a backslash is...{\\n} not ok')"
   ]
  },
  {
   "cell_type": "code",
Jon Shadforth's avatar
Jon Shadforth committed
207
   "execution_count": 13,
Jon Shadforth's avatar
Jon Shadforth committed
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
   "metadata": {},
   "outputs": [],
   "source": [
    "# Enable next line to test...\n",
    "# print(f'Nor is the {#} characeter')"
   ]
  },
  {
   "cell_type": "markdown",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## Categorised examples"
   ]
  },
  {
   "cell_type": "markdown",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "### Alignment and padding\n",
    "\n",
    "Alignment control involves an optional fill characeter followed by an alighnment type:\n",
    "* < Left aligned (default)\n",
    "* &gt; Right-aligned\n",
    "* = Padding after the sign and before the digits\n",
    "* ^ Centred"
   ]
  },
  {
   "cell_type": "code",
Jon Shadforth's avatar
Jon Shadforth committed
241
   "execution_count": 14,
Jon Shadforth's avatar
Jon Shadforth committed
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": "Simple\nLeft padding                      [              Popeye]\nLeft padding with custom pad-chr  [..............Popeye]\nRight padding                     [Popeye              ]\nRight padding with custom pad-chr [Popeye..............]\nCentred                           [.......Popeye.......]\nTruncated                         [Pop]\nTruncated and centred             [........Pop.........]\nPadding before digits (spaces)    [               12.34]\nPadding before digits (zeroes)    [00000000000000012.34]\nPadding before digits (spaces)    [-              12.34]\nPadding before digits (zeroes)    [-0000000000000012.34]\n"
    }
   ],
   "source": [
    "print(f\"{'Simple'}\")\n",
    "print(f'Left padding                      [{name:>20}]')\n",
    "print(f'Left padding with custom pad-chr  [{name:.>20}]')\n",
    "print(f'Right padding                     [{name:<20}]')\n",
    "print(f'Right padding with custom pad-chr [{name:.<20}]')\n",
    "print(f'Centred                           [{name:.^20}]')\n",
    "print(f'Truncated                         [{name:.3}]')\n",
    "print(f'Truncated and centred             [{name:.^20.3}]')\n",
    "print(f'Padding before digits (spaces)    [{12.34:=20}]')\n",
    "print(f'Padding before digits (zeroes)    [{12.34:=020}]')\n",
    "print(f'Padding before digits (spaces)    [{-12.34:=20}]')\n",
    "print(f'Padding before digits (zeroes)    [{-12.34:=020}]')"
   ]
  },
  {
   "cell_type": "markdown",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## Numbers"
   ]
  },
  {
   "cell_type": "markdown",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "### Sign display"
   ]
  },
  {
   "cell_type": "code",
Jon Shadforth's avatar
Jon Shadforth committed
285
   "execution_count": 15,
Jon Shadforth's avatar
Jon Shadforth committed
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": "Display sign, always              [              +12.34]\nDisplay sign, negative only       [               12.34]\nDisplay sign, always              [              -12.34]\nDisplay sign, negative only       [              -12.34]\nLeading space for positive        [ 12.34]\nLeading minus sign for negative   [-12.34]\n"
    }
   ],
   "source": [
    "print(f'Display sign, always              [{12.34:+20}]')\n",
    "print(f'Display sign, negative only       [{12.34:-20}]')\n",
    "print(f'Display sign, always              [{-12.34:+20}]')\n",
    "print(f'Display sign, negative only       [{-12.34:-20}]')\n",
    "print(f'Leading space for positive        [{12.34: }]')\n",
    "print(f'Leading minus sign for negative   [{-12.34: }]')"
   ]
  },
  {
   "cell_type": "markdown",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "### Thousands separator"
   ]
  },
  {
   "cell_type": "code",
Jon Shadforth's avatar
Jon Shadforth committed
314
   "execution_count": 16,
Jon Shadforth's avatar
Jon Shadforth committed
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": "No formatting:                      1000000\nComma thousands separator:          1,000,000\nUnderscore separator:               1_000_000\nLocale-aware  thousands separator:  1000000\n"
    }
   ],
   "source": [
    "value = 1000000\n",
    "print(f'No formatting:                      {value}')\n",
    "print(f'Comma thousands separator:          {value:,}')\n",
    "print(f'Underscore separator:               {value:_}')\n",
    "print(f'Locale-aware  thousands separator:  {value:n}')"
   ]
  },
  {
   "cell_type": "markdown",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "### Binary, octal and hexadecimal"
   ]
  },
  {
   "cell_type": "code",
Jon Shadforth's avatar
Jon Shadforth committed
342
   "execution_count": 19,
Jon Shadforth's avatar
Jon Shadforth committed
343 344 345 346 347
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
Jon Shadforth's avatar
Jon Shadforth committed
348
     "text": "Decimal:                               65537\nBinary:                                10000000000000001\nOctal:                                 200001\nHex:                                   10001\nHex (uppercase):                       10001\n\nBinary (alternate):                    0b10000000000000001\nOctal (alternate):                     0o200001\nHex (alternate):                       0x10001\nHex (uppercase, alternate):            0X10001\n\nBinary, underscore seperator:          1_0000_0000_0000_0001\nOctal, underscore seperator:           20_0001\nHex, underscore seperator:             1_0001\nHex, uppercase, underscore seperator:  1_0001\n\nExample: hex with prefix and padding:  0x00010001\n"
Jon Shadforth's avatar
Jon Shadforth committed
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
    }
   ],
   "source": [
    "value = 65537\n",
    "print(f'Decimal:                               {value}')\n",
    "print(f'Binary:                                {value:b}')\n",
    "print(f'Octal:                                 {value:o}')\n",
    "print(f'Hex:                                   {value:x}')\n",
    "print(f'Hex (uppercase):                       {value:X}')\n",
    "print()\n",
    "print(f'Binary (alternate):                    {value:#b}')\n",
    "print(f'Octal (alternate):                     {value:#o}')\n",
    "print(f'Hex (alternate):                       {value:#x}')\n",
    "print(f'Hex (uppercase, alternate):            {value:#X}')\n",
    "print()\n",
    "print(f'Binary, underscore seperator:          {value:_b}')\n",
    "print(f'Octal, underscore seperator:           {value:_o}')\n",
    "print(f'Hex, underscore seperator:             {value:_x}')\n",
Jon Shadforth's avatar
Jon Shadforth committed
367 368 369
    "print(f'Hex, uppercase, underscore seperator:  {value:_X}')\n",
    "print()\n",
    "print(f'Example: hex with prefix and padding:  0x{value:=08x}')"
Jon Shadforth's avatar
Jon Shadforth committed
370 371 372 373 374 375 376 377 378 379 380 381 382
   ]
  },
  {
   "cell_type": "markdown",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "### Floating point notation"
   ]
  },
  {
   "cell_type": "code",
Jon Shadforth's avatar
Jon Shadforth committed
383
   "execution_count": 18,
Jon Shadforth's avatar
Jon Shadforth committed
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": "No formatting:              1234.5678\nFixed-point to 2 dp:        1234.57\nFixed-point to 8 dp:        1234.56780000\nFixed-point :               1.2e+03\nInvalid without formatting: nan\nFixed-point with f:         nan\nFixed-point with F:         NAN\nInvalid without formatting: inf\nFixed-point with f:         inf\nFixed-point with F:         INF\n"
    }
   ],
   "source": [
    "import math\n",
    "value = 1234.5678\n",
    "\n",
    "print(f'No formatting:              {value}')\n",
    "print(f'Fixed-point to 2 dp:        {value:.2f}')\n",
    "print(f'Fixed-point to 8 dp:        {value:.8f}')\n",
    "print(f'Fixed-point :               {value:.2g}')\n",
    "\n",
    "print(f'Invalid without formatting: {math.nan}')\n",
    "print(f'Fixed-point with f:         {math.nan:f}')\n",
    "print(f'Fixed-point with F:         {math.nan:F}')\n",
    "print(f'Invalid without formatting: {math.inf}')\n",
    "print(f'Fixed-point with f:         {math.inf:f}')\n",
    "print(f'Fixed-point with F:         {math.inf:F}')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "### Exponent notation"
   ]
  },
  {
   "cell_type": "code",
Jon Shadforth's avatar
Jon Shadforth committed
420
   "execution_count": 1,
Jon Shadforth's avatar
Jon Shadforth committed
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": "No formatting:                          1234.5678\nExponent notation (default precision):  1.234568e+03\nExponent notation, precision 3:         1.235e+03\nExponent notation, E instead of e:      1.234568E+03\n"
    }
   ],
   "source": [
    "import math\n",
    "value = 1234.5678\n",
    "width = 10\n",
    "precision = 4\n",
    "\n",
    "print(f'No formatting:                          {value}')\n",
    "print(f'Exponent notation (default precision):  {value:e}')\n",
    "print(f'Exponent notation, precision 3:         {value:.3e}')\n",
    "print(f'Exponent notation, E instead of e:      {value:E}')"
   ]
  },
  {
   "cell_type": "markdown",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## Percentages"
   ]
  },
  {
   "cell_type": "code",
Jon Shadforth's avatar
Jon Shadforth committed
452
   "execution_count": 2,
Jon Shadforth's avatar
Jon Shadforth committed
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": "Percentage: [90.000000%]\nPercentage: [90.00%]\n"
    }
   ],
   "source": [
    "print(f'Percentage: [{0.9:%}]')\n",
    "print(f'Percentage: [{0.9:.2%}]')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## Value conversion"
   ]
  },
  {
   "cell_type": "code",
Jon Shadforth's avatar
Jon Shadforth committed
484
   "execution_count": 3,
Jon Shadforth's avatar
Jon Shadforth committed
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": "Using str:   45.1°\nUsing repr:  45.123456 degrees, 0.7875528770787904 radians\nMulti-line converted to ascii     ['Line 1\\nCaf\\xe9\\nLine 3']\n"
    }
   ],
   "source": [
    "class Angle(object):\n",
    "\n",
    "    def __init__(self, degrees):\n",
    "        self._degrees = degrees\n",
    "\n",
    "    def __str__(self):\n",
    "        return f'{self._degrees:0.1f}°'   \n",
    "\n",
    "    def __repr__(self):\n",
    "        return f'{self._degrees} degrees, {math.radians(self._degrees)} radians'\n",
    "\n",
    "multi_line = 'Line 1\\nCafé\\nLine 3'\n",
    "a = Angle(45.123456)\n",
    "print(f'Using str:   {a}')\n",
    "print(f'Using repr:  {a!r}')\n",
    "print(f'Multi-line converted to ascii     [{multi_line!a}]')"
   ]
  },
  {
   "cell_type": "markdown",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "### Date and time\n",
    "\n",
    "See the main [date and page](https://docs.python.org/3.8/library/datetime.html#module-datetime) and also the [format codes](https://docs.python.org/3.8/library/datetime.html#strftime-and-strptime-format-codes) for much more info."
   ]
  },
  {
   "cell_type": "code",
Jon Shadforth's avatar
Jon Shadforth committed
525
   "execution_count": 4,
Jon Shadforth's avatar
Jon Shadforth committed
526 527 528 529 530
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
Jon Shadforth's avatar
Jon Shadforth committed
531
     "text": "Reverse date, good for sorted filenames: 2020-01-30 at 17-31-35\nTime including milliseconds: 17:31:35.884\n\nWeekday as locale’s abbreviated name:                             Thu\nWeekday as locale’s full %X:                                      Thursday\nWeekday as a decimal number, where 0 is Sunday and 6 is Saturday: 4\nDay of the month as a zero-padded decimal number:                 30\nMonth as locale’s abbreviated name.:                              Jan\nMonth as locale’s full name:                                      January\nMonth as a zero-padded decimal number:                            01\nYear without century as a zero-padded decimal number:             20\nYear with century as a decimal number:                            2020\nHour (24-hour clock) as a zero-padded decimal number:             17\nHour (12-hour clock) as a zero-padded decimal number:             05\nLocale’s equivalent of either AM or PM:                           PM\nMinute as a zero-padded decimal number:                           31\nSecond as a zero-padded decimal number:                           35\nMicrosecond as a decimal number, zero-padded on the left:         884137\nUTC offset in the form +HHMM or -HHMM #1:                         \nTime zone name (empty string if the object is naive):             \nDay of the year as a zero-padded decimal number:                  030\nWeek number of the year #2:                                       04\nWeek number of the year #3:                                       04\nLocale’s appropriate date and time representation:                Thu Jan 30 17:31:35 2020\nLocale’s appropriate date representation:                         01/30/20\nLocale’s appropriate time representation:                         17:31:35\n\n"
Jon Shadforth's avatar
Jon Shadforth committed
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
    }
   ],
   "source": [
    "import datetime\n",
    "\n",
    "# Note #1: Empty string if the the object is naive\n",
    "\n",
    "# Note #2: Sunday as the first day of the week as a zero padded decimal number.\n",
    "# All days in a new year preceding the first Sunday are considered to be in week 0\n",
    "\n",
    "# Note #3: Monday as the first day of the week as a decimal number.\n",
    "# All days in a new year preceding the first Monday are considered to be in week 0\n",
    "\n",
    "date = datetime.datetime.now()\n",
    "\n",
    "print(f'Reverse date, good for sorted filenames: {date:%Y}-{date:%m}-{date:%d} at {date:%H}-{date:%M}-{date:%S}')\n",
    "print(f'Time including milliseconds: {date:%X}.{int(date.microsecond / 1000):=03}')\n",
    "print()\n",
    "print(f'Weekday as locale’s abbreviated name:                             {date:%a}')\n",
    "print(f'Weekday as locale’s full %X:                                      {date:%A}')\n",
    "print(f'Weekday as a decimal number, where 0 is Sunday and 6 is Saturday: {date:%w}')\n",
    "print(f'Day of the month as a zero-padded decimal number:                 {date:%d}')\n",
    "print(f'Month as locale’s abbreviated name.:                              {date:%b}')\n",
    "print(f'Month as locale’s full name:                                      {date:%B}')\n",
    "print(f'Month as a zero-padded decimal number:                            {date:%m}')\n",
    "print(f'Year without century as a zero-padded decimal number:             {date:%y}')\n",
    "print(f'Year with century as a decimal number:                            {date:%Y}')\n",
    "print(f'Hour (24-hour clock) as a zero-padded decimal number:             {date:%H}')\n",
    "print(f'Hour (12-hour clock) as a zero-padded decimal number:             {date:%I}')\n",
    "print(f'Locale’s equivalent of either AM or PM:                           {date:%p}')\n",
    "print(f'Minute as a zero-padded decimal number:                           {date:%M}')\n",
    "print(f'Second as a zero-padded decimal number:                           {date:%S}')\n",
    "print(f'Microsecond as a decimal number, zero-padded on the left:         {date:%f}')\n",
    "print(f'UTC offset in the form +HHMM or -HHMM #1:                         {date:%z}')\n",
    "print(f'Time zone name (empty string if the object is naive):             {date:%Z}')\n",
    "print(f'Day of the year as a zero-padded decimal number:                  {date:%j}')\n",
    "print(f'Week number of the year #2:                                       {date:%U}')\n",
    "print(f'Week number of the year #3:                                       {date:%W}')\n",
    "print(f'Locale’s appropriate date and time representation:                {date:%c}')\n",
    "print(f'Locale’s appropriate date representation:                         {date:%x}')\n",
    "print(f'Locale’s appropriate time representation:                         {date:%X}')\n",
    "print()\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "execution_count": 67,
   "metadata": {},
   "outputs": [],
   "source": [
    "### Experiments!\n",
    "\n",
    "Use the cell below to noodle with the value and the standard format specifier"
   ]
  },
  {
   "cell_type": "code",
Jon Shadforth's avatar
Jon Shadforth committed
590
   "execution_count": 5,
Jon Shadforth's avatar
Jon Shadforth committed
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": "Format specifier:  .<+20,.3f\nOutput:            +12,345.679.........\n"
    }
   ],
   "source": [
    "value = 12345.6789\n",
    "\n",
    "fill = '.'\n",
    "align = '<'\n",
    "sign = '+'\n",
    "width = 20\n",
    "grouping_option = ','\n",
    "precision = '.3'\n",
    "type = 'f'\n",
    "\n",
    "print(f'Format specifier:  {fill}{align}{sign}{width}{grouping_option}{precision}{type}')\n",
    "print(f'Output:            {value:{fill}{align}{sign}{width}{grouping_option}{precision}{type}}')"
   ]
  },
Jon Shadforth's avatar
Jon Shadforth committed
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": "'0x00000011'"
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "f'0x{17:=08x}'"
   ]
  },
Jon Shadforth's avatar
Jon Shadforth committed
632 633 634 635 636 637 638 639 640
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ]
}