[Tutor] Clarification on .format() Method and Negative Indices in Python
Xingyuan Shi
xingyuanshi17 at gmail.com
Tue Sep 24 22:23:21 EDT 2024
Dear Python Tutor Team,
I hope you are having a great day.
I have been learning more about Python’s string formatting, and I came
across an interesting issue regarding the .format() method. Specifically, I
was curious as to why negative indices like {-1} are not supported in this
method, while negative indexing works perfectly with lists and other
sequences in Python.
For instance, I attempted to use the following code:
print("{-1},{-1},{-1}".format(20, "example", 3.14))
I expected the placeholders {-1} to behave similarly to negative indices in
lists, but it resulted in an error. I understand that .format() relies on
positional arguments, but I wonder if there was a specific design rationale
behind not allowing negative indices here. Could you shed some light on
this design choice?
Thank you very much for your time and for developing such an incredible
language that I thoroughly enjoy learning.
Best regards,
Stone
More information about the Tutor
mailing list