Extract Numbers from String

Extract all numbers from string.

AdvancedPhase 5 - Category 5: Advanced String LogicExample 4 of 14
extract-numbers-from-string.py
1# Take string input
2s = input("Enter a string: ")
3
4# Extract numbers
5numbers = []
6current_num = ""
7for char in s:
8 if char.isdigit():
9 current_num += char
10 else:
11 if current_num:
12 numbers.append(int(current_num))
13 current_num = ""
14if current_num:
15 numbers.append(int(current_num))
16
17print(f"Numbers: {numbers}")

Output

Enter a string: Hello123World456
Numbers: [123, 456]

What's going on

Build numbers character by character.

Key Concepts:

Track current number being built
Add digit to current number
Convert to int when complete