473,672 Members | 2,589 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

checking if a string contains a number

Hi,
I have a string like,
s1 = '12e3'
s2 = 'junk'

Now before converting these values to float, I want to check if they
are valid numbers.

s1.isdigit returns False.

Is there any other function which would return True for s1 and False
for s2.

Thanks

--
Suresh
Dec 20 '05 #1
4 3516
You should probably work through the tutorials.

Use a try block:

try: x=float(s)
except ValueError:
print 'Non-numeric value %s found' % s

-Larry Bates

Suresh Jeevanandam wrote:
Hi,
I have a string like,
s1 = '12e3'
s2 = 'junk'

Now before converting these values to float, I want to check if they
are valid numbers.

s1.isdigit returns False.

Is there any other function which would return True for s1 and False
for s2.

Thanks

--
Suresh

Dec 20 '05 #2
On Tue, Dec 20, 2005 at 07:16:46PM +0530, Suresh Jeevanandam wrote:
s1 = '12e3'
s2 = 'junk'
Is there any other function which would return True for s1 and False
for s2.


isinstance(12e3 , (int, float))
--
Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991
=============== =============== =============== =============== ============
Dec 20 '05 #3
On Tue, 20 Dec 2005 19:16:46 +0530, Suresh Jeevanandam wrote:
Hi,
I have a string like,
s1 = '12e3'
s2 = 'junk'

Now before converting these values to float, I want to check if they
are valid numbers.
Just try converting them:

float_list = []
for s in string_list:
try:
float_list.appe nd(float(s))
except ValueError:
# ignore bad strings
pass
do_something_wi th_floats(float _list)

s1.isdigit returns False.
"2" is a digit. "23" is two digits. You want something like s1.isfloat(),
but why bother checking first? Just Do It.
Is there any other function which would return True for s1 and False
for s2.


From an interactive interpreter, call dir(s1). That will give you a list
of string methods. Then call help(s1.method) to learn what that method
does.
--
Steven.

Dec 20 '05 #4
On Tue, 20 Dec 2005 15:55:37 +0100, egbert wrote:
On Tue, Dec 20, 2005 at 07:16:46PM +0530, Suresh Jeevanandam wrote:
s1 = '12e3'
s2 = 'junk'
Is there any other function which would return True for s1 and False
for s2.


isinstance(12e3 , (int, float))


That won't work, because s1 is a *string*, not a float. The original
poster is asking how to check whether the string can be converted to a
float successfully before actually trying to convert it to a float.
--
Steven.

Dec 20 '05 #5

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

Similar topics

4
11780
by: Tom Esker | last post by:
I've got Javascript in a form that adds up all of the numbers in a column of form fields and displays a total. It works great if every field has an initial value of 0, but if any of them are null, "NaN" displays as the total. I tried to add a test for a null value with the intent to skip adding that field to the accumulator for one iteration of the "for" loop, but it doesn't work. Can anyone tell me what I'm doing wrong? Below is the...
9
11219
by: booksnore | last post by:
I am writing some code to search for strings that contain every letter of the alphabet. At the moment I am using the method below to check to see if a string contains every letter of the alphabet. I wanted to use a regular expression but I could not find an ‘AND’ operator within the regular expression – so I need something like match true if string contains ‘a’ and ‘b’ and ‘c’ and ‘d’ ..etc,etc. If anyone has any thoughts on how I can...
4
2374
by: Patient Guy | last post by:
Does anyone have any coding rules they follow when doing argument checking? When arguments fail during check, do you return from the call with an ambiguous return value, or do you throw exceptions?
42
2791
by: =?Utf-8?B?UGxheWE=?= | last post by:
I have an if statement that isn't working correctly and I was wondering how I check for a blank string. My Code Example if me.fieldname(arrayIndex) = "" then ----- end if When I do this and there is no characters in the variable it does not enter my IF statement like I would think it should. How do I properly check for a
13
14974
by: nishit.gupta | last post by:
Is their any 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" Thnx
11
4265
by: Bryan Crouse | last post by:
I am looking a way to do error checking on a string at compile time, and if the string isn't the correct length have then have the compiler throw an error. I am working an embedded software that will require individual builds for each device so that the device serial number is contained in the program memory. To do this, the C application must be compiled with the serial number assigned to a variable within the source code file. I...
7
1828
by: =?Utf-8?B?QnJpYW4gQ29vaw==?= | last post by:
I need to check to see if a string contains two different constraints. I currently use this else if statement to look for the first constraints; else if (lines.Contains("]CODELINE_INDICATION_MSG")) { i += 112; rtbDoc.Select(i, 2); rtbDoc.SelectionFont = new Font(rtbDoc.SelectionFont, rtbDoc.SelectionFont.Style ^ style); rtbDoc.SelectionColor = Color.DarkBlue;
4
16295
by: Hamish | last post by:
Hey I'm new to python, but I have used a fair bit of C and Perl I found Perls regex's to be very easy to use however I don't find Pythons regexes as good. All I am trying to do is detect if there is a number in a string. I am reading the string from an excel spread sheet using the xlrd
21
11366
by: ningxin | last post by:
Hi, i am currently taking a module in c++ in the university, and was given an assignment. because i have no prior background on the subject, everything is kind of new to me. i have tried for quite some time and still not able to get the solution out. so i hope you guys can help me out. of course i am not expecting a full solution, but i would greatly appreciate it if anyone can suggest to me what should i do. i am very new to this subject so...
0
8504
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
8419
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,...
0
8945
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8643
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
8697
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
5720
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
4439
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2840
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1839
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.