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

问题描述 投票:0回答:1

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

    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

其中的东西是稍后将作为值添加到字典中的东西。

python
1个回答
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'}
© www.soinside.com 2019 - 2024. All rights reserved.