| | |
Recognize the amount of digits in a string
Thread Solved |
•
•
Join Date: Jun 2009
Posts: 8
Reputation:
Solved Threads: 0
I'm struggeling with a problem which probably is farely easy to solve. I just cant find a simple way to do it.
I want to be able to recognize the occurance of digits in a string. Lets say the string looks like:
Now I want to be able to pick out '123' and 987 from those strings. The numbers vary so I dont want to search for specific numbers, just find the digits..
Edit: In the end I want to be able to recognize the amount of digits (using len) but maybe there's a faster way to do this?
I want to be able to recognize the occurance of digits in a string. Lets say the string looks like:
Python Syntax (Toggle Plain Text)
file_Name1 = 'abc123de' file_Name2 = 'qwe987rty'
Now I want to be able to pick out '123' and 987 from those strings. The numbers vary so I dont want to search for specific numbers, just find the digits..
Edit: In the end I want to be able to recognize the amount of digits (using len) but maybe there's a faster way to do this?
I'd say split the string into a list and use the filter method:
EDIT:
If you need to know what filter does, lookie here:
python Syntax (Toggle Plain Text)
file_Name1 = 'abc123de' # store that string as a list of characters L1 = list(file_Name1) # call filter on it using a lambda expression L1 = filter(lambda x: x in '1234567890', L1) # L1 now = ['1', '2', '3'] num_digits = len(L1)
EDIT:
If you need to know what filter does, lookie here:
Python Syntax (Toggle Plain Text)
filter(function, iterable) Construct a list from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If iterable is a string or a tuple, the result also has that type; otherwise it is always a list. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed. Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)] if function is not None and [item for item in iterable if item] if function is None. See itertools.filterfalse() for the complementary function that returns elements of iterable for which function returns false.
Last edited by shadwickman; Jun 24th, 2009 at 8:02 am.
"Two good old boys in a fire-apple red convertible. Stoned. Ripped. Twisted. Good people."
- Hunter S. Thompson
my photography
- Hunter S. Thompson
my photography
•
•
Join Date: Jun 2009
Posts: 2
Reputation:
Solved Threads: 1
you can compare the string character by charater
and then use the function which convert the string to int. If the result is true then that perticular character is number else
it is string.
Eg. in VB
String s1="abcd145df78"
int length=len(s1)
string ss=""
for i=0 to length-1
a=mid(s1,i,1)
if isnumeric(a) then
ss=ss & " " & a
next
and then use the function which convert the string to int. If the result is true then that perticular character is number else
it is string.
Eg. in VB
String s1="abcd145df78"
int length=len(s1)
string ss=""
for i=0 to length-1
a=mid(s1,i,1)
if isnumeric(a) then
ss=ss & " " & a
next
Why did you post VB code? This is the Python forum. Regardless, please put it in [code][/code] tags.
"Two good old boys in a fire-apple red convertible. Stoned. Ripped. Twisted. Good people."
- Hunter S. Thompson
my photography
- Hunter S. Thompson
my photography
Shadwickmans solution using filter is a very good one!
Another way is to use regular expressions...
Without further ado, here's a simple example using regular expressions:
The code above is a little clunky and inelegant as we're storing variables we probably don't need to be..But it is only an example!
If you only wanted to know the number of digits in the string you could shorten the above example to 3 lines of code:
As you can see, in the above code we're munging several operations into one command at the end of the print statement.
If you want to find out more about using regular expressions check out the documentation that ships with python (hit F1 in idle!) and search for 'regular expression' you'll find out all you need to know!
Cheers for now,
Jas.
Another way is to use regular expressions...
Without further ado, here's a simple example using regular expressions:
PYTHON Syntax (Toggle Plain Text)
#example using regular expressions import re # here's the string we'll be searching: myStr = "abc123def" # search through the string using a regular expression # this regex will return any decimal digits (0-9) it finds in the string temp = re.search('[0-9]+', myStr) # you could also use the following regex: # m = re.search('\d+', myStr) # which is another way of writing the above expression # now lets process the results of the search... result = temp.group() numDigits = len(result) print "In the string:", myStr, "- There were", numDigits, "numerical digits found, the digits were", result
The code above is a little clunky and inelegant as we're storing variables we probably don't need to be..But it is only an example!
If you only wanted to know the number of digits in the string you could shorten the above example to 3 lines of code:
PYTHON Syntax (Toggle Plain Text)
# regular expressions example 2 import re myStr="abc123def" print "Number of digits =", len( (re.search('[0-9]+', myStr)).group() )
As you can see, in the above code we're munging several operations into one command at the end of the print statement.
If you want to find out more about using regular expressions check out the documentation that ships with python (hit F1 in idle!) and search for 'regular expression' you'll find out all you need to know!
Cheers for now,
Jas.
There are 10 types of people in this world.....
Those who understand binary .....
And those who don't!
Those who understand binary .....
And those who don't!
Sorry to continue a thread that's been marked solved, but I thought I'd better note that the solution I posted would only match a single block of numbers.
If we changed the value of myStr to "abc123def456", the examples I previously posted would only pick up the first block of digits (123).
In case you've got more than one block of digits in the string and you want to get them all you'd need to use findall() instead of search()....(See below)
Thought I'd better mention it!
If we changed the value of myStr to "abc123def456", the examples I previously posted would only pick up the first block of digits (123).
In case you've got more than one block of digits in the string and you want to get them all you'd need to use findall() instead of search()....(See below)
PYTHON Syntax (Toggle Plain Text)
import re myStr="abc123def456" result = re.findall('[0-9]+', myStr) numDigits = 0 for i in result: numDigits+=len(i) print "String:", myStr print "Digits found:", result print "Number of digits =", numDigits
Thought I'd better mention it!
There are 10 types of people in this world.....
Those who understand binary .....
And those who don't!
Those who understand binary .....
And those who don't!
![]() |
Similar Threads
- count digits in string (C++)
- string to float (C)
- Recognize the word in a string (JavaScript / DHTML / AJAX)
- Here is the doc file for the assignment (C++)
- Counting the amount of numbers in one integer? (C++)
- String Problem (Visual Basic 4 / 5 / 6)
- Adding decimal numbers together? (C)
- string comparisions (C++)
- How to add a prepayment amount to message string (Java)
Other Threads in the Python Forum
- Previous Thread: Re-execute main program
- Next Thread: Replace words in a file
| Thread Tools | Search this Thread |
abrupt ansi anti approximation assignment avogadro backend beginner binary bluetooth calculator character cmd code customdialog cx-freeze data decimals dictionaries dictionary directory dynamic error examples exe file float format function gnu graphics gui heads homework http ideas import input itunes java launcher leftmouse line linux list lists loop module mouse number numbers output parsing path pointer port prime programming progressbar projects push py2exe pygame pyglet pyqt python random recursion schedule screensaverloopinactive script scrolledtext sqlite ssh statistics string strings sudokusolver sum table terminal text thread threading time tlapse tricks tuple tutorial twoup ubuntu unicode urllib urllib2 variable ventrilo wikipedia write wxpython xlib





