如何检查字符串是否以负数和浮点数开头? [蟒蛇]

时间:2018-03-04 00:47:22

标签: python

我有一段看起来像这样的代码:

    loc2 = {}
    with open('loc.txt') as filename:
    for line in filename:
        a = line.strip()
        if a.replace('.','',1).isdigit():
            loc2[float(a[0])] = a[1:]
    return loc2

其中我需要检查一个数字[总是在文件loc.txt中的行的开头,并且总是单独在整行上],可以是负数,int或浮点数,以及将其作为键添加到字典中。有人可以帮帮我吗?不知道如何处理这个问题。我试过更换'。'空的空间,但它没有工作,也没有解决我的负数问题,显然。我仍然是python中的菜鸟。谢谢!

loc.txt的例子:

1
stuff
1.1
stuff
-4
stuff

其中stuff是稍后将作为值添加到字典中的内容。

1 个答案:

答案 0 :(得分:1)

您可以尝试使用try except语句。

loc2 = {}
with open('loc.txt') as filename:
    for i,line in enumerate(filename):
        # split the given line up by space into a list
        a = line.strip().split()
        try:
            # attempt to convert first part of line into float
            k = float(a[0])
            # assignment that key the value of the rest of the string
            loc2[k] = ' '.join(a[1:])
        except ValueError as ex:
            # actions performed when the line does not start with number
            print('Line %d did not start with a number.'%i)
        else:
            # actions performed when the float conversion was successful
            print('Key {} has been added with value: {}'.format(k,loc2[k]))

loc.txt文件:

-1 one
0 two
1.5 three
-5.708 four
test

<强>输出继电器:

Key -1.0 has been added with value: one
Key 0.0 has been added with value: two
Key 1.5 has been added with value: three
Key -5.708 has been added with value: four
Line 4 did not start with a number.

loc2内容

{-1.0: 'one', 0.0: 'two', 1.5: 'three', -5.708: 'four'}