-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Fix strformat precision handling for strings #7941
Fix strformat precision handling for strings #7941
Conversation
+1. That makes sense. You get to implement a feature without a "surprise API" for people crossing over to Nim. |
lib/pure/strformat.nim
Outdated
case spec.typ | ||
of 's', '\0': discard | ||
else: | ||
raise newException(ValueError, | ||
"invalid type in format string for string, expected 's', but got " & | ||
spec.typ) | ||
if spec.precision != -1: | ||
if spec.precision < runelen(value): | ||
value = value.runeSubstr(0, spec.precision) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It would be better if, instead of allocating a new string via slicing, this set the length of value
instead.
…/github.com/skilchen/Nim into fix_strformat_precision_handling_for_strings
@@ -558,12 +558,16 @@ proc format*(value: string; specifier: string; res: var string) = | |||
## sense to call this directly, but it is required to exist | |||
## by the ``&`` macro. | |||
let spec = parseStandardFormatSpecifier(specifier) | |||
var value = value |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This seems the wrong place to fix it, shouldn't alignString
be changed instead?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No, because alignString
is also used for floats that are already stringified to the requested "precision". For floats you don't want to deal with "precision" in alignString
.
IMHO alignString should just align strings and not modify the passed in string in any way.
Another attempt to bring the precision handling for strings closer to what python does.
The relevant part of the documentation is almost a literal copy from python:
python:
Nim:
I think it makes sense to also copy python's behavior in this case. The possibility to limit the number of characters in a formatted string is useful to produce fixed size columns in a simple textual report.
This example:
produces