[英]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.