Assume I have a string as follows: expression = '123 + 321'.
I am walking over the string character-by-character as follows: for p in expression. I am I am checking if p is a digit using p.isdigit(). If p is a digit, I’d like to grab the whole number (so grab 123 and 321, not just p which initially would be 1).
How can I do that in Python?
In C (coming from a C background), the equivalent would be:
int x = 0;
sscanf(p, "%d", &x);
// the full number is now in x
EDIT:
Basically, I am accepting a mathematical expression from a user that accepts positive integers, +,-,*,/ as well as brackets: ‘(‘ and ‘)’. I am walking the string character by character and I need to be able to determine whether the character is a digit or not. Using isdigit(), I can that. If it is a digit however, I need to grab the whole number. How can that be done?
The Python documentation includes a section on simulating
scanf, which gives you some idea of how you can use regular expressions to simulate the behavior ofscanf(orsscanf, it’s all the same in Python). In particular,r'\-?\d+'is the Python string that corresponds to the regular expression for an integer. (r'\d+'for a nonnegative integer.) So you could embed this in your loop asBut that still reflects a very C-like way of thinking. In Python, your iterator variable
pis really just an individual character that has actually been pulled out of the original string and is standing on its own. So in the loop, you don’t naturally have access to the current position within the string, and trying to calculate it is going to be less than optimal.What I’d suggest instead is using Python’s built in regexp matching iteration method:
and now
all_the_numbersis a list of string representations of all the integers in the expression. If you wanted to actually convert them to integers, then you could do this instead of the last line:Here I’ve used
finditerinstead offindallbecause you don’t have to make a list of all the strings before iterating over them again to convert them to integers.