【问题标题】:How can we understand if the value inside a String is an int or not in Python?在 Python 中,我们如何理解 String 中的值是否为 int?
【发布时间】:2020-11-07 08:49:12
【问题描述】:

我正在编写遇到问题的代码,如果存在则需要解决方案。 假设我们在 Python 中有一个包含整数值的 String 类型变量。 如:x='123' 我知道我们可以通过类型转换轻松地将其转换为 int。 但是,假设我们有以下列表。

x=['123','Spain']

Python 中是否有任何方法可以让我知道列表 x 的哪个元素是包含在字符串中的 Integer 以及哪个纯粹是 Object?

【问题讨论】:

标签: python types type-conversion


【解决方案1】:

我会推荐这种方法:

x = "123"
if x.isdigit():
    # int
elif x.replace(".","",1).isdigit():
    # float
else:
    # str

【讨论】:

  • elif x.replace(".","").isdigit(): 这个我不喜欢,考虑例如"1.2.3"。是浮动的吗?
【解决方案2】:

我假设您对this post 有类似的问题。

但是,从我的角度来看,对于更通用的解决方案(与语言无关),您应该了解更多关于正则表达式的信息,这里还有 the same question

【讨论】:

    猜你喜欢
    • 2020-11-18
    • 2011-08-02
    • 2012-06-24
    • 2021-02-20
    • 1970-01-01
    • 1970-01-01
    • 2011-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多