【问题标题】:How to convert str "6\u2009000" to int()如何将 str "6\u2009000" 转换为 int()
【发布时间】:2021-10-25 13:14:22
【问题描述】:

我有一个格式为“6\u2009000”的 str。 如何将其转换为 int?

如果我使用a = int(str, 10),我会得到:

ValueError: invalid literal for int() with base 10: '6\u2009000'

【问题讨论】:

  • \u2009 是一个 Unicode 序列。你希望看到什么输出?
  • U+2009 是 Unicode 字符“THIN SPACE”。 \u2009 是这种字符的 Python/JSON 表示。建议您在尝试将其作为数字处理之前从字符串中去除空格
  • btw 不要使用str 作为变量名,它是一个内置函数
  • int(str, 10) 从字符串中读取基于10 的数字。所以int("12", 3) 返回5。因为12 基于35
  • @MSH 是的,这有什么帮助?

标签: python unicode


【解决方案1】:

根据最新的 cmets,您可以这样做:

print(int('6\u2009000'.replace('\u2009', '_')))

或者只是:

print(int('6\u2009000'.replace('\u2009', '')))

后一种形式更可靠,因为它不依赖于 Unicode 字符的位置

【讨论】:

  • print(int(''.join('6\u2009000'.split())))
  • @Matiiss 这当然适用于这个例子
猜你喜欢
  • 2020-01-05
  • 1970-01-01
  • 1970-01-01
  • 2012-02-14
  • 2015-07-27
  • 1970-01-01
  • 2019-12-03
  • 2018-06-20
  • 2017-01-18
相关资源
最近更新 更多