繁体   English   中英

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

[英]How do I check if a string starts with a negative number and a float? [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中的行首,并且始终位于整行中),然后将其添加到字典作为关键。 有人可以帮我吗? 不知道如何解决这个问题。 我试图替换“。” 带有空白空间,但这显然行不通,也无法解决我的负数问题。 我还是python的菜鸟。 谢谢!

loc.txt的示例:

1
stuff
1.1
stuff
-4
stuff

东西是东西,以后会作为值添加到字典中。

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

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'}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM