如何知道一个字符串是数字还是浮点数

时间:2019-04-12 04:06:18

标签: python python-3.x casting

我正在使用python3来接收字符串列表,并且我必须检查它们的元素是否为整数,浮点数或随机字符串以供将来使用。

<div id=showLat>

最好的方法是什么?任何推荐功能?

4 个答案:

答案 0 :(得分:1)

我会在这里使用try / except逻辑,在这里我尝试将字符串解析为一个int,如果它抛出异常,则将其解析为float,甚至抛出异常,都说它确实是一个字符串像这样。

def check_type(str):
    try:
        int(str)
        print(str, 'is a integer')
    except:
        try:
            float(str)
            print(str, 'is a float')
        except:
            print(str, 'is a string')

然后,当我在您的列表中执行它时,我会得到

lst = ['3', 'random2', '5.05', '1', 'Cool phrase']
for l in lst:
    check_type(l)
#3 is a integer
#random2 is a string
#5.05 is a float
#1 is a integer
#Cool phrase is a string

答案 1 :(得分:0)

尝试以下代码:

l1 = ['3', 'random2', '5.05','1','Cool phrase']
for ele in l1:
    if "." in ele and ele.replace('.', '').isdigit():
        print("%s is float"%ele)
    elif ele.isdigit():
        print("%s is int"%ele)
    else:
        print("%s is string"%ele)

输出:

3 is int 
random2 is string
5.05 is float 
1 is int
Cool phrase is string

答案 2 :(得分:-1)

获取类型详细信息的两种简单方法。

`list1 = [3, 'random2', '5.05','1','Cool phrase']
 list2 = [type(element ) for element in list1]
 print (list2)`

list1 = [3, 'random2', '5.05','1','Cool phrase']
for element in list1:
    print (type(element ))

答案 3 :(得分:-2)

您需要的是正则表达式。

Python的re [https://docs.python.org/3.7/library/re.html]模块可以为您提供帮助。 例如:

>>> re.match(r"\d+.\d+", '24.12')
<_sre.SRE_Match object; span=(0, 5), match='24.12'>
>>> re.match(r"\d+", 24)
<_sre.SRE_Match object; span=(0, 2), match='24'>
>>> re.match(r"\d+", 24.12)
None