Created
September 24, 2014 15:55
-
-
Save tansey/5b59d73c58587973844d to your computer and use it in GitHub Desktop.
Python-style string formatting in Julia with floating point support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function format(s, args...) | |
# Python-style string formatting with floating point support | |
# Note that this is 1-based to be more Julian | |
result = deepcopy(s) | |
for (i, x) in enumerate(args) | |
q = Regex("{$i(:\.([0-9])+f)?}") | |
next = result | |
for m in eachmatch(q, result) | |
val = x | |
if m.captures[2] != nothing | |
precision = parseint(m.captures[2]) | |
val = round(x * 10^precision) / 10.0^precision | |
end | |
next = replace(next, m.match, val) | |
end | |
result = next | |
end | |
result | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also note that this method is not about speed, it's about functionality. There are faster ways to do this for sure, but this is a quick and dirty solution that works like I wanted it to.