Learn How to Code with Python: Beginner to Advanced Guide
When working with text data in Python, you often encounter numbers embedded inside strings. This happens when reading user input, processing files, handling CSV data, or parsing logs. A string like `"Age: 42"` contains a number, but Python treats it entirely as text until you explicitly convert the numeric portion. To extract numbers, you must first isolate the numeric characters. This can be done using string methods such as `split()`, `strip()`, or by iterating over characters. Once isolated, you convert the string representation into a numeric type using `int()` or `float()`. If you try to convert a string that is not purely numeric (like `"42 years"`) directly using `int()`, Python raises a `ValueError`. Proper parsing means carefully cleaning the string before conversion. 2 It returns 42 It returns 0 It raises a ValueError What happens if you call `int("42 years")` directly in Python? Sometimes numbers appear with extra spaces. For example, `" 15 "` contains a valid number surrounded by whitespace. Fortunately, Python’s `int()` and `float()` functions automatically ignore leading and trailing spaces. This means you usually do not need to call `strip()` before converting. However, calling `strip()` is still good practice when cleaning inconsistent input data from users or files. Understanding how whitespace behaves during parsing prevents unnecessary preprocessing steps and keeps code simpler. 1 It raises an error because of spaces It converts successfully to 15 It returns the string unchanged Which statement about converting `" 15 "` using `int()` is correct? Parsing floating-point numbers follows the same principle as integers. If you have a string like `"3.14"`, calling `float("3.14")` correctly converts it to a floating-point number. However, attempting `int("3.14")` fails because `"3.14"` is not a valid integer literal. The decimal point makes it incompatible with the integer format. Choosing between `int()` and `float()` depends entirely on the numeric structure of the string. 1 It returns 3 It raises a ValueError It returns 3.14 What happens when you call `int("3.14")`? Sometimes numbers are embedded within larger text. For example, `"Order #1234 confirmed"` contains digits mixed with letters and symbols. Direct conversion is impossible without extracting the numeric portion. One common approach is to iterate over characters and keep only digits using `str.isdigit()`. Another method involves using regular expressions to find numeric patterns more flexibly. The key principle is separation before conversion. 0 `str.isdigit()` `str.upper()` `str.find()` Which method helps identify numeric characters in a string? Negative numbers introduce another detail. The string `"-25"` can be converted directly using `int("-25")`, because the minus sign is recognized as part of a valid integer literal. However, if you manually filter digits using `isdigit()`, the minus sign will be removed unless handled explicitly. This can accidentally change `"-25"` into `"25"`. When parsing numbers, always consider whether signs must be preserved. 1 It removes decimal points It ignores the minus sign It converts strings to floats Why might using `isdigit()` alone cause issues with negative numbers? Parsing numbers from user input is extremely common. The `input()` function always returns a string, even if the user types digits. Therefore, conversion is always required before performing arithmetic operations. If you forget conversion and try to add two input values, Python concatenates them as strings instead of adding numerically. This subtle bug can lead to logical errors in programs that appear syntactically correct. 2 int float str If `a = input()` and the user types 5, what is the type of `a`? Handling invalid input safely is critical. When converting strings to numbers, you should use a `try`/`except` block to catch `ValueError`. This allows the program to continue running even if the input is malformed. Instead of crashing, you can display a helpful message or request input again. Robust parsing always assumes that input may be incorrect. 1 TypeError ValueError IndexError Which exception is raised when `int()` fails to convert a string? Numbers may contain commas as thousands separators, such as `"1,000"`. Directly calling `int("1,000")` raises a `ValueError` because commas are not valid characters in integer literals. To handle this, you must remove commas before conversion. This can be done using `replace(",", "")`. Preprocessing formatting characters is often necessary when dealing with financial or formatted data. 0 Replace commas with empty strings Convert to float first Use `strip()` What must you do before converting `"1,000"` using `int()`? Scientific notation may also appear in strings, such as `"1e3"`. The `float()` function understands scientific notation and correctly converts `"1e3"` into `1000.0`. However, `int("1e3")` raises a `ValueError`, because scientific notation is not valid for direct integer conversion. Understanding numeric formats expands your parsing capabilities. 1 1 1000.0 An error What does `float("1e3")` return? Sometimes you need to extract multiple numbers from a single string, such as `"Width: 10 Height: 20"`. In this case, you must identify and separate both numeric substrings. Regular expressions are powerful tools for this. Using a pattern like `\d+` allows you to find all sequences of digits in the string. Parsing multiple values requires pattern recognition rather than simple splitting. 0 Regular expressions `upper()` `len()` Which tool is especially powerful for extracting multiple numeric patterns from a string?