在 Python 中将数学表达式字符串拆分为标记 [英] Splitting a math expression string into tokens in Python

查看:28
本文介绍了在 Python 中将数学表达式字符串拆分为标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多python字符串比如"A7*4""Z3+8""B6/11",我想拆分这些字符串,以便它们在列表中,格式为 ["A7", "*", "4"], ["B6", "/", "11"] 等.我使用了很多不同的拆分方法,但我认为我只需要在有数学符号的地方执行拆分,例如 /,*,+,-.我还需要去掉空格.

目前我正在使用代码 re.split(r'(\D)', "B6/11"),它返回 ['', 'B', '6', ' ', '', '/', '', ' ', '11'].相反,我想找回 ["B6", "/", "11"].

解决方案

你应该在 字符集 [+-/*] 从字符串中去除空格后:

<预><代码>>>>进口重新>>>def mysplit(mystr):... return re.split("([+-/*])", mystr.replace(" ", ""))...>>>mysplit("A7*4")['A7', '*', '4']>>>mysplit("Z3+8")['Z3', '+', '8']>>>mysplit("B6/11")['B6', '/', '11']>>>

I have a lot of python strings such as "A7*4", "Z3+8", "B6 / 11", and I want to split these strings so that they would be in a list, in the format ["A7", "*", "4"], ["B6", "/", "11"], etc. I have used a lot of different split methods but I think I need to just perform the split where there is a math symbol, such as /,*,+,-. I would also need to strip out the whitespace.

Currently I am using the code re.split(r'(\D)', "B6 / 11"), which is returning ['', 'B', '6', ' ', '', '/', '', ' ', '11']. Instead I want to get back ["B6", "/", "11"].

解决方案

You should split on the character set [+-/*] after removing the whitespace from the string:

>>> import re
>>> def mysplit(mystr):
...     return re.split("([+-/*])", mystr.replace(" ", ""))
...
>>> mysplit("A7*4")
['A7', '*', '4']
>>> mysplit("Z3+8")
['Z3', '+', '8']
>>> mysplit("B6 / 11")
['B6', '/', '11']
>>>

这篇关于在 Python 中将数学表达式字符串拆分为标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆