0

On the W3resource website there is a beginner exercise #10 which asks for the following:

Write a Python program to display the examination schedule. (extract the date from exam_st_date). Go to the editor exam_st_date = (11, 12, 2014)

Sample Output : The examination will start from : 11 / 12 / 2014*

in the sample solution the following code is given:

exam_st_date = (11,12,2014)
print( "The examination will start from : %i / %i / %i"%exam_st_date)

what does the %i mean or do and how does it interact with tuples in python?

Pedro Maia
  • 2,666
  • 1
  • 5
  • 20
  • It means they're using an old string formatting method – Sayse Jan 14 '22 at 16:01
  • 1
    Have you tried to run that code? It should be self-explanatory except perhaps for the fact that for output %i and %d are synonymous – DarkKnight Jan 14 '22 at 16:02
  • `%i` is a placeholder for a signed integer decimal value. – John Gordon Jan 14 '22 at 16:08
  • `i` has nothing to do with tuples, per se. However since a tuple argument was given to the `%` operator, then each element of the tuple is "assigned", from left to right, to a different `%i` in the format string. – chepner Jan 14 '22 at 16:13
  • New code should use either the `format` method or f-strings rather than using the `%` operator for string formatting. `%` is still useful to know, though, for understanding how the `logging` module constructs log messages. – chepner Jan 14 '22 at 16:17

1 Answers1

1

This is the legacy string formatting syntax. This page describes the accepted formatting specifiers - %i formats the argument as a "signed integer decimal".

The modern equivalent is the str.format function, or f-strings.

0x5453
  • 12,753
  • 1
  • 32
  • 61
  • This doesn't explain what `%i` means – Sayse Jan 14 '22 at 16:02
  • Heh true, I also skipped over the `%i` part when reading the question. – Peter Jan 14 '22 at 16:03
  • @Sayse See my edit. – 0x5453 Jan 14 '22 at 16:15
  • How would the code look like if the current string formatting syntax was used? – irakli Jojua Jan 14 '22 at 18:30
  • A direct translation might look like: `print("The examination will start from : {} / {} / {}".format(*exam_st_date))` or `print(f"The examination will start from : {exam_st_date[0]} / {exam_st_date[1]} / {exam_st_date[2]}")`. If I were writing it, I would use a [`datetime.date`](https://docs.python.org/3/library/datetime.html#date-objects) instead of a tuple, which (among other benefits) lets you use [date-aware formatting specifiers](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior), e.g. `print(f"The examination will start from : {exam_st_date:%d / %m / %Y}")` – 0x5453 Jan 14 '22 at 19:41