473,372 Members | 970 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,372 software developers and data experts.

A way of checking if a string contains a number

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
module

then I would like to test if this string has a number in it

ie.
import xlrd
import re

doesHaveNumber = re.compile('[0-9]')
string1 = ABC 11

regularExpressionCheck = doesHaveNumber.search(string1)

This will get the right result but then I would like to use the result
in an IF statement and have not had much luck with it.

if regularExpressionCheck != "None"
print "Something"

the result is that it prints every line from the spreadsheet to output
but I only want the lines from the spreadsheet to output.

Is there a way I can drop the regular expression module and just use
built in string processing?

Why si the output from checks in teh re module either "None" or some
crazy memory address? Couldn't it be just true or false?



Dec 12 '07 #1
4 16270
Hamish wrote:
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
module

then I would like to test if this string has a number in it

ie.
import xlrd
import re

doesHaveNumber = re.compile('[0-9]')
string1 = ABC 11

regularExpressionCheck = doesHaveNumber.search(string1)

This will get the right result but then I would like to use the result
in an IF statement and have not had much luck with it.

if regularExpressionCheck != "None"
print "Something"

the result is that it prints every line from the spreadsheet to output
but I only want the lines from the spreadsheet to output.

Is there a way I can drop the regular expression module and just use
built in string processing?

Why si the output from checks in teh re module either "None" or some
crazy memory address? Couldn't it be just true or false?


regularExpressionCheck won't ever contain the characters "None". The result
if doesHaveNumber.search(string1) is a match object not a string. IMHO regular
expressions are overkill for the task you describe. You may be better served to
just try to convert it to whatever number you want.

try:
value=int(string1)

except ValueError:
# do whatever you want for non integers here

else:
# do whatever you want for integers here

Or use string methods:

if string1.isdigit():
print "digits found"
else:
print "alphas found"

-Larry
Dec 12 '07 #2
:
[...] IMHO regular
expressions are overkill for the task you describe. You may be better served to
just try to convert it to whatever number you want.

try:
value=int(string1)
Fails for the OP's example:
>>string1 = "ABC 11"
int(string1)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): ABC 11
Or use string methods:

if string1.isdigit():
print "digits found"
else:
print "alphas found"
Again ...
>>string1.isdigit()
False

If you were desperate to avoid regexes, this works:
>>max([(d in string1) for d in "0123456789"])
True

.... but it's not exactly legible.

-[]z.
Dec 12 '07 #3
Larry Bates a écrit :
IMHO
regular expressions are overkill for the task you describe.
There are cases where regexps are the right tool, and according to the
exemple given, this may be one (now it's of course hard to tell without
seeing a decent sample of real data...).
Dec 12 '07 #4
On Dec 12, 10:59 pm, "Zero Piraeus" <sche...@gmail.comwrote:
:
[...] IMHO regular
expressions are overkill for the task you describe. You may be better served to
just try to convert it to whatever number you want.
try:
value=int(string1)

Fails for the OP's example:
>>string1 = "ABC 11"
>>int(string1)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): ABC 11
Or use string methods:
if string1.isdigit():
print "digits found"
else:
print "alphas found"

Again ...
>>string1.isdigit()
False

If you were desperate to avoid regexes, this works:
>>max([(d in string1) for d in "0123456789"])
True

... but it's not exactly legible.
How about:
>>string1 = "ABC 11"
any(c.isdigit() for c in string1)
True
Dec 13 '07 #5

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

Similar topics

4
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,...
9
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....
4
by: Suresh Jeevanandam | last post by:
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.
4
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...
42
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...
13
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
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...
7
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...
21
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...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.