【问题标题】:Converting integer to string in Julia在 Julia 中将整数转换为字符串
【发布时间】:2017-03-10 21:43:59
【问题描述】:

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

我知道这是非常基本的,并尝试寻找正确的方法来做到这一点here,但无法弄清楚。

【问题讨论】:

标签: string floating-point type-conversion julia


【解决方案1】:

你应该使用:

b = string(a)

b = repr(a)

string 函数可用于使用print 从任何值创建字符串,而repr 使用showall。在Int64 的情况下,这是等效的。

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

编辑

对于整数,您可以在过去版本的 Julia 中将它们转换为字符串,也可以使用 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"

【讨论】:

  • 小修正:string 可用于将任何值转换为AbstractString 的子类型,即string 的输出不是总是 类型为@987654340 @.
  • binhexbase 等已被弃用。在不同的基础上打印的新方法是:string(42, base = 2)。它还支持填充。
猜你喜欢
  • 2020-05-16
  • 1970-01-01
  • 2020-12-19
  • 1970-01-01
  • 2010-12-27
  • 2012-02-21
  • 2010-12-31
相关资源
最近更新 更多