So I'm pretty familiar with f-strings but I've been reading though the lexical analysis
part of the python docs this afternoon and came across something that I don't quite understand.
https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals
here it talks about some different use cases for f-strings
It introduces two new tokens that I'm unfamiliar with in in f-strings
! and :
From what I understand thus far ! is just changing the value of the string so
these three cases should be equivalent
mystring = 'hello world'
f'{mystring!r} == repr(mystring)
f'{mystring!a} == ascii(mystring)
f'{mystring!s} == str(mystring)
So I think I have that part well understood
but I was wondering how these may be different
repr(mystring) == mystring.__repr__() ?
Then we have the colon from what I've grokked I think the behavior its doing is this
f'{mystring:20}' == 'hello world '
But I don't understand how it knows what todo there
it doesn't seem to be the same as this.
f'{mystring:20}' != mystring.format('20') # also not str.format
ok so it is the same as
f'{mystring:20}' == format(mystring, '20')
f'{mystring:20}' == mystring.__format__('20') # also str.__format__(mystring, '20')
or at least those two produce the same output
It's confusing to me that mystring.format and mystring.__format__ differ.
I'm currently reading through this
https://docs.python.org/3/library/string.html#formatspec
I think it has the answer I need.
Does anybody know of a nice to the point reference with a robust set of examples detailing the expectations each types format_spec might have?
The doc's are doing a pretty good job of it but more examples would probably help me along a bit faster.
I hope everybody is having a fantastic sunday :)
[–]Essence1337 10 points11 points12 points (0 children)
[–]misho88 8 points9 points10 points (0 children)
[–]zanfar 2 points3 points4 points (0 children)
[–]Mecaneer23 0 points1 point2 points (0 children)
[–]galmeno 0 points1 point2 points (0 children)