繁体   English   中英

如何确定字符串中是否有浮点数

[英]How can I identify if a float within a string

我旨在打印用户输入列表中每个元素的列表。 输出的列表将符号标识为字符串,将数字标识为浮点数,以将元素基本比较为浮点数和字符串。 如果列表中的数字已经是浮点数,则无法正确打印输出。

expression_list = []
expression = "(3.1+2)*5"

for index in expression:
    try: 
        float_index = float(index)
        expression_list.append(float_index)
    except ValueError:
        expression_list.append(index)
print(expression_list)     

我期望输出为['(', 3.1, '+', 2.0, ')', '*', 5.0]而不是['(', 3.0, '.', 1.0, '+', 2.0, ')', '*', 5.0]

我会在这里使用re.findall

expression = "(3.1+2)*5"
output = re.findall(r'[()]|[^\w]+|(?:\d+(?:\.\d+)?)', expression)
print(output)

['(', '3.1', '+', '2', ')', '*', '5']

使用的模式是:

[()] | [^\w]+ | (?:\d+(?:\.\d+)?)

这符合:

[()]              an opening or closing parenthesis, as a separate match
[^\w]             any other non word character
(?:\d+(?:\.\d+)?  a number, with or without a decimal component

发生这种情况是因为for index in expression:的for循环for index in expression:遍历字符串的每个字符,因此不检查3.1是否为浮点型,而是通过将其转换来检查3是浮点型还是1是浮点型,并且float('3')=3.0 ,因此您看到了结果。

In [8]: expression_list = [] 
   ...: expression = "(3.1+2)*5" 
   ...:  
   ...:  
   ...: for index in expression: 
   ...:     print(index) 
   ...:                                                                                                                                                                           
(
3
.
1
+
2
)
*
5

也许您可以按照提姆的答案提供给您的浮点数,运算符和方括号的方式拆分字符串。

假设您有该输出,您的代码将按预期工作

import re

expression_list = []
expression = "(3.1+2)*5"

literals = re.findall(r'[()]|[^\w]+|(?:\d+(?:\.\d+)?)', expression)

for index in literals:
    try:
        float_index = float(index)
        expression_list.append(float_index)
    except ValueError:
        expression_list.append(index)
print(expression_list)

如您所愿,输出将为['(', 3.1, '+', 2.0, ')', '*', 5.0]

暂无
暂无

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

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