---
# System prepended metadata

title: Extract only numbers from text
tags: [kite]

---

###### tags: `kite`

# Extract only numbers from text

## Visual Summary

```mermaid
graph LR
    A['text_1_with_2_numbers_3']  
    A -- func: extract_numbers -->  B('123')
```



## Main Concept

For extracting only numbers from a Python string, we could categorize string characters into two groups.

1. Characters that can be casted to digits.
2. Characters that can not be casted to digits.



Python standard library has `str.isdigit()` function where `str` is just any string, the function will return **True** if all characters in that string are digits, **False** otherwise.

**Example:**

```python
>>> print('a'.isdigit())
False
```



## Example 1 (Simple function)

**Simple function to extract only numbers from string.**

```python
def extract_numbers(text_and_numbers : str) -> str:
    """Extract only numbers from string.
    Args:
    	text_and_numbers (str): a string contains mix of digits & letters.
    Return:
    	digits_only (str): string of extracted digits.
    """
    
    # Empty string to hold the extracted digits.
    digits_only = ""
    
    # Iterate over each char in the string.
    for char in text_and_numbers:
        # Check if the char is digit. 
        if char.isdigit():
            # Append the char to {text_only} string.
        	digits_only += char
        
    return digits_only
```



**Test the function**

```python
>>> mixed_string = "text_1_with_2_numbers_3"
>>> digits = extract_numbers(mixed_string)
>>> print(digits)
123
```



## Example 2 (Advanced)

**You can achieve the same result with less effort using list comprehensions**  

```python
mixed_string = "text_1_with_2_numbers_3"

# This will return list of digits characters 
numbers_list = [char for char in mixed_string if char.isdigit()]

# Convert the list to a string
digits = "".join(numbers_list)
```

```python
>>> print(numbers_list)
['1', '2', '3']
>>> print(digits)
123
```

------

# Putting an if-elif-else statement on one line

It's possible to shorten a simple if-condition in a single line, although it's not recommended if it has a lot chains as that will be less readable.

a **one-line if conditions** is also called **(ternary conditional operator)** with the following structure.
`<expression1> if <condition> else <expression2>`



## Example 1 (Simple)

> Check if the weather condition is **cold** or **hot** by temperature degree.

```python
>>> temp = 40
>>> weather_condition = "Cold" if temp < 20 else "Hot"
>>> print(weather_condition)
Hot
```



## Example 2 (Advanced)

> What if we want to return "Good" if it's not that hot or that cold! 

```python
>>> temp = 25
>>> weather_condition = "Cold" if temp < 20 else "Good" if temp < 30 else "Hot"
>>> print(weather_condition)
Good
```

Note that, Conditions evaluation direction is from left to right.
So the previous example is equal to:

```python
if temp < 30:
    if temp < 20:
        print("Cold")
    else:
        print("Good")
else:
    print("Hot")
```



