473,799 Members | 3,416 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

numeric expression from string?

Hello,

I have a string input from the user, and want to parse it to a number, and would like
to know how to do it. I would like to be able to accept arithmetic operations, like:

'5+5'
'(4+3)*2'
'5e3/10**3'

I thought of using eval, which will work, but could lead to bad security problems
(not that it's a big deal in my app, but still...)

string.atof won't do the job. Is there a preferred way of doing this?
thanks,
Brian Blais
--
-----------------

bb****@bryant.e du
http://web.bryant.edu/~bblais
Feb 4 '06 #1
8 1765
Brian Blais schrieb:
Hello,

I have a string input from the user, and want to parse it to a number,
and would like to know how to do it. I would like to be able to accept
arithmetic operations, like:

'5+5'
'(4+3)*2'
'5e3/10**3'

I thought of using eval, which will work, but could lead to bad security
problems (not that it's a big deal in my app, but still...)

string.atof won't do the job. Is there a preferred way of doing this?


No. If you already know about the pro and cons of eval, either go for it
- or if it bothers you, write a parser using pyparsing and evaluate the
expressions yourself.

Regards,

Diez
Feb 4 '06 #2
On Sat, 04 Feb 2006 06:48:11 -0500, Brian Blais wrote:
Hello,

I have a string input from the user, and want to parse it to a number, and would like
to know how to do it. I would like to be able to accept arithmetic operations, like:

'5+5'
'(4+3)*2'
'5e3/10**3'

I thought of using eval, which will work, but could lead to bad security problems
(not that it's a big deal in my app, but still...)
It is good to be cautious. Big thumbs up. But what exactly are you worried
about? Do you think your users might enter something Evil and break their
own system? I'd suggest that's not your problem, and besides, it is hard
to think of anything they could do with eval that they couldn't do by
exiting your app and running something Evil in their shell prompt.

Are you running this script as a cgi script? Then remote users might use
eval to break your system, and you are right to avoid it.

Are you worried about angry customers calling you up with bizarre bugs,
because they entered something weird into their input string? One
possible way to avoid those problems is to validate the string before
passing it to eval:

goodchars = "0123456789 +-/*()eE."
for c in user_input:
if c not in goodchars:
raise ValueError("Ill egal character detected!")
result = eval(user_input )
string.atof won't do the job. Is there a preferred way of doing this?


Look into PyParsing:

http://cheeseshop.python.org/pypi/pyparsing/1.3.3

If you read back over the Newsgroup archives, just in the last week or so,
there was a link to a PyParsing tutorial.
--
Steven.

Feb 4 '06 #3
Brian Blais wrote:
Hello,

I have a string input from the user, and want to parse it to a number,
and would like to know how to do it. I would like to be able to accept
arithmetic operations, like:

'5+5'
'(4+3)*2'
'5e3/10**3'

I thought of using eval, which will work, but could lead to bad security
problems (not that it's a big deal in my app, but still...)

string.atof won't do the job. Is there a preferred way of doing this?
thanks,
Brian Blais

I have no idea if it is the right thing for what you need, so it would
be nice to get response if it is or not:
http://www.strout.net/python/pythonica.html

Claudio
Feb 4 '06 #4
Brian Blais wrote:
I have a string input from the user, and want to parse it to a
number, and would like to know how to do it. I would like to be able
to accept arithmetic operations, like:

'5+5'
'(4+3)*2'
'5e3/10**3'

I thought of using eval, which will work, but could lead to bad
security problems (not that it's a big deal in my app, but still...)

eval() is the preferred way unless you have serious security reasons:
def calc(s): .... try:
.... return float(eval(s, dict(__builtins __=None)))
.... except Exception, e:
.... raise ValueError, "error during expression evaluation: %s" % e
.... calc("3**4") 81.0 calc("58+34*4") 194.0 calc("58+34*4+a ") Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 5, in calc
ValueError: error during expression evaluation: name 'a' is not defined calc("object.__ class__") Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 5, in calc
ValueError: error during expression evaluation: name 'object' is not defined calc("3.__class __") Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 5, in calc
ValueError: error during expression evaluation: unexpected EOF while parsing
(line 1) calc("type(3)._ _class__")

Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 5, in calc
ValueError: error during expression evaluation: name 'type' is not defined
Of course, one can still bring your system to its knees when
"1000**10000000 00000000"...
--
Giovanni Bajo
Feb 4 '06 #5
Steven D'Aprano wrote:

It is good to be cautious. Big thumbs up. But what exactly are you worried
about? Do you think your users might enter something Evil and break their
own system? I'd suggest that's not your problem, and besides, it is hard
to think of anything they could do with eval that they couldn't do by
exiting your app and running something Evil in their shell prompt.
yeah, I guess when you think about it, there really isn't a problem. I figured that
someone might accidentally do damage to their system with an unchecked eval.

Are you running this script as a cgi script? Then remote users might use
eval to break your system, and you are right to avoid it.


no I am not, but it is good to know how to deal with it in this case too.
thanks!
bb

--
-----------------

bb****@bryant.e du
http://web.bryant.edu/~bblais
Feb 6 '06 #6
Brian Blais <bb****@bryant. edu> wrote:
someone might accidentally do damage to their system with an unchecked eval.


Nah, it takes malice and deliberation to damage a system from an eval.
Alex
Feb 7 '06 #7
Steven wrote:
Do you think your users might enter something Evil and break their own system?


That's not usually how it works.

How it usually works is:

1. Innocent code-monkey writes nifty applet, posts on usenet.
2. Innocent but dull-witted framework manufacturer includes nifty
applet in Next Big Thing framework.
2. Innocent webmaster uses framework to design entire website,
dragging and dropping input boxes validated by nifty applet all over
the place.
3. Budding malevolent self-deceived "just fooling around" script
kiddie enters evil string into vulnerable buffer passed nifty applet,
taking down innocent webmaster's system. Posts astonishment on
#dickwar3z irc channel.
4. Genuinely malevolent wiseguy/blackmailer/terrorist blackhat stores
sploit for later inclusion in rootkit-laying worm suite.
5. Randal Schwartz goes to jail.

--Blair

Feb 7 '06 #8
Steven wrote:
Do you think your users might enter something Evil and break their own system?


That's not usually how it works.

How it usually works is:

1. Innocent code-monkey writes nifty applet, posts on usenet.
2. Innocent but dull-witted framework manufacturer includes nifty
applet in Next Big Thing framework.
2. Innocent webmaster uses framework to design entire website,
dragging and dropping input boxes validated by nifty applet all over
the place.
3. Budding malevolent self-deceived "just fooling around" script
kiddie enters evil string into vulnerable buffer passed nifty applet,
taking down innocent webmaster's system. Posts astonishment on
#dickwar3z irc channel.
4. Genuinely malevolent wiseguy/blackmailer/terrorist blackhat stores
sploit for later inclusion in rootkit-laying worm suite.
5. Randal Schwartz goes to jail.

--Blair

Feb 7 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
42393
by: Aaron DeLoach | last post by:
I may have cross-posted this... :-( I'm a VB programmer getting *way* to deep into this wonderful new JS venture. I looked around for a function like VBs' IsNumeric without much success. I had to roll my own. Does anyone see any bugs in this? function IsNumeric(expression) { var nums = "0123456789";
30
3697
by: Dr John Stockton | last post by:
It has appeared that ancient sources give a method for Numeric Date Validation that involves numerous tests to determine month length; versions are often posted by incomers here. That sort of code seems unnecessarily long. For some while, the following approach has been given here :- function ValidDate(y, m, d) { // m = 0..11 ; y m d integers, y!=0
2
4549
by: Ray Stevens | last post by:
I would like to quickly strip out all non-numeric characters from a string (including whitespace) into a new string (i.e., remove the edit mask). Would RegEx be the best way to do this and, if so, what is the syntax?
6
1822
by: Peter Afonin | last post by:
Hello, Should be a pretty simple question: I need to validate a string. It must be numeric and contain exactly 12 characters. I know how to do it in code, but I'd like to use a validation control. Should I use a Regular expression validator? What expression should I use? I checked http://www.regxlib.com, but couldn't find exactly what I need.
11
4581
by: Keith | last post by:
I apologize for those of you who think I'm posting on the same topic. It is not that I don't appreciate all of your comments - and I'm definitely reading them all - but I think I have a differing opinion of how I want to handle the 'user experience' in the application I'm creating. While I know I could allow the user to enter in number and alpha text - in a text box - and then tell them when the execuate a command "This is not numeric data", I...
5
1961
by: Takeadoe | last post by:
I've got a favor to ask - Consider the following numeric field: 511 6805 3205 403 I need to make 2 new numeric fields from this variable, call it CS
4
1818
by: CrazyCruzan | last post by:
Hello, I have a table that has a string field "ANUM" that has values that always begin with 089. Then the 3 characters; 089, are followed by between 3 or 4 characters. So a typical value in this field might be 089213 or 0895146. There will never be more than 4 characters, which follows that the total number of characters will not exceed 7. What I need is an expression that will "filter" out the 089 values, leaving the remainder behind....
14
2937
by: nishit.gupta | last post by:
Is their any single fuction available in C++ that can determine that a string contains a numeric value. The value cabn be in hex, int, float. i.e. "1256" , "123.566" , "0xffff" , It can also contain zero
6
2038
by: priravi | last post by:
Hi, I'm having a numeric expression say "((2*3)-(3*4+5))" returned from a method as a string value... now i have to evaluate the expression and store it in an integer vaariable. Convert.toint or int.parse is not working and since i'm new to .net development i have no idea of how else to convert this.Please do help me regarding this
0
9688
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9544
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10238
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10030
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9077
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6809
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5467
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3761
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2941
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.