Re: Clarification on .format() Method and Negative Indices in Python

"avi.e.gross--- via Tutor" <[email protected]> Sun, 6 Oct 2024 16:43:10 -0400
Newsgroups gmane.comp.python.tutor
Message-ID <[email protected]>
Hi,

I'm not responding to what was designed for this one of many ways to print but suggesting a way to get what you want another way.

Consider using an fstring as in this example:

>>> example="ABCDE"
>>> example[-1]
'E'
>>> print(f"last char in example is: {example[-1]}")
last char in example is: E

Anything in an f-string between curly braces is evaluated and replaced and negative numbers are supported.

Of course, if someday they change your other way, feel free to use that.

And, of course, you can preprocess what you want before using your print method into a small variable, as another workaround.


-----Original Message-----
From: Tutor <[email protected]> On Behalf Of Xingyuan Shi via Tutor
Sent: Tuesday, September 24, 2024 10:23 PM
To: [email protected]
Subject: [Tutor] Clarification on .format() Method and Negative Indices in Python

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
_______________________________________________
Tutor maillist  -  [email protected]
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


_______________________________________________
Tutor maillist  -  [email protected]
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor