I am parsing some data where the standard format is something like 10 pizzas. Sometimes, data is input correctly and we might end up with 5pizzas instead of 5 pizzas. In this scenario, I want to parse out the number of pizzas.
The naïve way of doing this would be to check character by character, building up a string until we reach a non-digit and then casting that string as an integer.
num_pizzas = ""
for character in data_input:
if character.isdigit():
num_pizzas += character
else:
break
num_pizzas = int(num_pizzas)
This is pretty clunky, though. Is there an easier way to split a string where it switches from numeric digits to alphabetic characters?
You ask for a way to split a string on digits, but then in your example, what you actually want is just the first numbers, this done easily with
itertools.takewhile():This makes a lot of sense – what we are doing is taking the character from the string while they are digits. This has the advantage of stopping processing as soon as we get to the first non-digit character.
If you need the later data too, then what you are looking for is
itertools.groupby()mixed in with a simple list comprehension:If you then want to make one giant number: