Elixir将字符串解析为整数 [英] Elixir parsing string to integer

查看:75
本文介绍了Elixir将字符串解析为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将字符串列表转换为整数列表.这是代码:

I try to convert a list of strings into a list of integers. Here's the code:

list = ["114"]
list |> Enum.map(&String.to_integer(&1))

但是最后一行返回'r'.而 String.to_integer("114")返回 114 我尝试了 Integer.parse/1 ,但是它也给了我'r'(其字符代码为114):

But the last line returns 'r'. While String.to_integer("114") returns 114 I tried Integer.parse/1, but it also gave me 'r' (which its character code is 114):

list
|> Enum.map(&Integer.parse(&1))
|> Enum.map(fn {num, _} -> num end)

为什么?

推荐答案

正如其他评论所指出的那样,这种令人困惑的行为是Elixir的人性化"结果.人物.简而言之,Elixir(出于历史原因)可以将未编码的字符串存储为整数列表(称为字符列表").得出的结论是,当列表的所有成员都是ASCII范围内的整数(即0-127)时,则Elixir使用每个整数的对应代码点来格式化显示( 114 对应于<例如code> r .

As the other comments have pointed out, this confusing behavior is the result of Elixir "humanizing" charlists. In a nutshell, Elixir (for historical reasons) can store un-encoded strings as lists of integers (called "charlists"). The take-away is that when all the members of a list are integers in the ASCII range (i.e. 0-127), then Elixir formats the display using the corresponding codepoints for each integer (114 corresponds to r, for example).

请参阅此答案以获取类似的解释:

See this answer for similar explanation: Why does for x <- 3..4, do: x * 3 return '\t\f' in Elixir?

这篇关于Elixir将字符串解析为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆