简体   繁体   English

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

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

I aim to print a list of every element inside a user-inputted list. 我旨在打印用户输入列表中每个元素的列表。 The outputted list identifies symbols as strings, and numbers as floats, to basically compare elements as floats and strings. 输出的列表将符号标识为字符串,将数字标识为浮点数,以将元素基本比较为浮点数和字符串。 If the number in the list is already a float, the output is not printed properly. 如果列表中的数字已经是浮点数,则无法正确打印输出。

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)     

I expect the output to be ['(', 3.1, '+', 2.0, ')', '*', 5.0] instead I get ['(', 3.0, '.', 1.0, '+', 2.0, ')', '*', 5.0] 我期望输出为['(', 3.1, '+', 2.0, ')', '*', 5.0]而不是['(', 3.0, '.', 1.0, '+', 2.0, ')', '*', 5.0]

I would use re.findall here: 我会在这里使用re.findall

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

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

The pattern used is: 使用的模式是:

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

This matches: 这符合:

[()]              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

This is happening because your for loop for index in expression: iterates through every character of the string, so it is not checking if 3.1 is a float, it checks if 3 is a float and 1 is a float by converting it, and float('3')=3.0 , hence you see the result. 发生这种情况是因为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

Perhaps you can split the strings in a manner which extract out the floats and the operators and brackets, which Tim's answer has provided to you. 也许您可以按照提姆的答案提供给您的浮点数,运算符和方括号的方式拆分字符串。

Assuming you have that output, your code will work as expected 假设您有该输出,您的代码将按预期工作

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)

The output will be ['(', 3.1, '+', 2.0, ')', '*', 5.0] as you expected! 如您所愿,输出将为['(', 3.1, '+', 2.0, ')', '*', 5.0]

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

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