Reputation: 467
I am looking for a function that does the following rending:
f("2") = 2²
f("15") = 2¹⁵
I tried f(s) = "2\^($s)"
but this doesn't seem to be a valid exponent as I can't TAB.
Upvotes: 5
Views: 369
Reputation: 1313
this should be a little faster, and uses replace
:
function exp2text(x)
two = '2'
exponents = ('⁰', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹')
#'⁰':'⁹' does not contain the ranges
exp = replace(x,'0':'9' =>i ->exponents[Int(i)-48+1])
#Int(i)-48+1 returns the number of the character if the character is a number
return two * exp
end
in this case, i used the fact that replace
can accept a Pair{collection,function}
that does:
if char in collection
replace(char,function(char))
end
Upvotes: 1
Reputation: 69949
You can try e.g.:
julia> function f(s::AbstractString)
codes = Dict(collect("1234567890") .=> collect("¹²³⁴⁵⁶⁷⁸⁹⁰"))
return "2" * map(c -> codes[c], s)
end
f (generic function with 1 method)
julia> f("2")
"2²"
julia> f("15")
"2¹⁵"
(I have not optimized it for speed, but I hope this is fast enough with the benefit of being easy to read the code)
Upvotes: 7