我想在Julia中将整数转换为字符串。
当我尝试:
a = 9500
b = convert(String,a)
我得到错误:
ERROR: LoadError: MethodError: Cannot `convert` an object of type Int64 to an object of type String
This may have arisen from a call to the constructor String(...),
since type constructors fall back to convert methods.
in include_from_node1(::String) at ./loading.jl:488
in process_options(::Base.JLOptions) at ./client.jl:265
in _start() at ./client.jl:321
while loading ..., in expression starting on line 16
我不确定为什么不能将Int64转换为字符串。
我尝试将其定义a
为不同的类型,例如a = UInt64(9500)
,但得到类似的错误。
我知道这是非常基本的,因此尝试在此处寻找正确的方法,但无法解决。
您应该使用:
b = string(a)
要么
b = repr(a)
string
函数可以用于使用print
和repr
使用从任何值创建字符串showall
。在Int64
这种情况下是等效的。
实际上,这可能是convert无法正常工作的原因-因为有多种方法可以将整数转换为字符串,具体取决于基数的选择。
编辑
对于整型,你可以在朱莉娅的过去版本将它们转换为字符串也使用bin
,dec
,hex
,oct
或base
。
在Julia 1.0以后的版本中,您可以使用带有整数关键字参数的字符串函数在不同的基础上进行转换base
。另外,您还具有bitstring
给出数字的文字位表示的功能。这里有些例子:
julia> string(100)
"100"
julia> string(100, base=16)
"64"
julia> string(100, base=2)
"1100100"
julia> bitstring(100)
"0000000000000000000000000000000000000000000000000000000001100100"
julia> bitstring(UInt8(100))
"01100100"
julia> string(100.0)
"100.0"
julia> string(100.0, base=2)
ERROR: MethodError: no method matching string(::Float64; base=2)
Closest candidates are:
string(::Any...) at strings/io.jl:156 got unsupported keyword argument "base"
string(::String) at strings/substring.jl:146 got unsupported keyword argument "base"
string(::SubString{String}) at strings/substring.jl:147 got unsupported keyword argument "base"
...
Stacktrace:
[1] top-level scope at none:0
julia> bitstring(100.0)
"0100000001011001000000000000000000000000000000000000000000000000"
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句