在Julia中将整数转换为字符串

36

我想在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),但是收到了类似的错误信息。

我知道这很基础,并尝试在这里寻找正确的方法,但无法弄清楚。


任何用途 - daycaster
重复的问题:如何在Julia中将任何类型转换为字符串。投票关闭。 - Colin T Bowers
1个回答

43

你应该使用:

b = string(a)
或者
b = repr(a)

string 函数可以使用 printrepr 使用 showall 来从任何值创建字符串。对于 Int64,这是等效的。

实际上,这可能是转换不起作用的原因-因为有许多将整数转换为字符串的方法,这取决于基数的选择。

编辑

对于整数,你可以在 Julia 1.0 的旧版本中使用 bindechexoctbase 将它们转换为字符串。

在 Julia 1.0 之后,您可以使用 string 函数,针对整数使用 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"

1
小修正:string 可以用于将任何值转换为 AbstractString 的子类型,也就是说,string 的输出并不总是 String 类型。 - Colin T Bowers
1
binhexbase等已过时。在不同进制下打印的新方法是:string(42, base = 2)。它还支持填充。 - cmc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接