Mathew K Analytics

Lesson 35 · Python for Data Science

3 - String Cleaning and Data Type Conversion in Python

In this lesson, we will learn how to clean up messy strings and turn them into useful data types. These skills help us prepare real-world data for analysis…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb
 

Welcome to String Cleaning and Data Type Conversion in Python!#

In this lesson, we will learn how to clean up messy strings and turn them into useful data types.

These skills help us prepare real-world data for analysis almost every project needs them.

By the end, you will be able to process and transform text like a pro!

# Let us make a string with extra spaces and numbers
raw_data = "    42 apples   "
print(raw_data)
    42 apples   

Why Clean Strings?#

Messy text can cause errors and make analysis harder.

For example, spaces and strange characters might confuse our code.

We often want to remove these before we can use the text.

# Remove spaces from both ends
cleaned = raw_data.strip()
print(cleaned)
42 apples
# Remove just the left side spaces
left_cleaned = raw_data.lstrip()
print(left_cleaned)
42 apples   
# Remove just the right side spaces
right_cleaned = raw_data.rstrip()
print(right_cleaned)
    42 apples

Removing Other Messy Characters#

Sometimes, data has symbols or newlines (like '\n') that we do not want.

We can use replace to take them out.

# String with a newline and dollar sign
messy = " $99.99\n "
step1 = messy.strip()         # Remove leading and trailing spaces
step2 = step1.replace("$", "")  # Remove dollar sign
step3 = step2.replace('\n', '')   # Remove newline
print(step3)
99.99
# Strings can sometimes have tabs too
tabby = "\t 123 hello \t"
no_tabs = tabby.replace('\t', '')
print(no_tabs.strip())
123 hello

Turn Clean Strings into Numbers#

Data we clean often needs to be a number, not just text.

We can turn a string like '42' into an integer so we can do math.

# Let us convert a cleaned string to an integer
num_str = '   1001   '
clean_num_str = num_str.strip()    # Remove spaces
number = int(clean_num_str)        # Convert to integer
print(number)
1001
# Converting to a float (decimal number)
dec_str = " 3.1416 "
clean_dec_str = dec_str.strip()
dec_number = float(clean_dec_str)
print(dec_number)
3.1416
# What if conversion fails?
bad_str = 'twelve'
try:
    val = int(bad_str)
except ValueError:
    val = None
    print('Could not convert!')
    
Could not convert!
# Ask the user for input and clean it
user_input = input('Enter your age: ')
age_clean = user_input.strip()
age_num = int(age_clean)
print('Your age plus five is:', age_num + 5)
Your age plus five is: 28
 

Changing Strings to Upper or Lower Case#

Sometimes you want all text to match, for easy comparison.

Python lets you change case simply.

# Upper and lower case string cleaning
messy_case = "  PyTHon RuLEs!  "
clean_case = messy_case.strip()
upper = clean_case.upper()
lower = clean_case.lower()
print('Upper:', upper)
print('Lower:', lower)
Upper: PYTHON RULES!
Lower: python rules!
# Remove many characters at once using translate
import string
sample = 'hello!! 42%* apples###'
remove = str.maketrans('', '', string.punctuation + '0123456789')
cleaned = sample.translate(remove)
print(cleaned.strip())
hello  apples
# A simple mini-project: Clean a messy price list
prices = [' $3.99 ', '\n4.50$', '5.00', ' 2.25 ']
clean_prices = []
for p in prices:
    temp = p.strip().replace('$', '').replace('\n', '')
    clean_prices.append(float(temp))
print(clean_prices)
[3.99, 4.5, 5.0, 2.25]
# MINI-PROJECT PART 2: Total and average of cleaned prices
total = sum(clean_prices)
average = total / len(clean_prices)
print('Total:', total)
print('Average:', round(average, 2))
Total: 15.74
Average: 3.94
# Trouble: What if we forget to strip before converting?
example = ' 404 '
number = int(example)    # This will work, but always check for extra spaces!
print(number)
404
# Challenge: Clean and add two user-entered numbers
num1 = input('Enter a messy number: ')
num2 = input('Enter another messy number: ')
n1 = float(num1.strip().replace('$', '').replace(',', ''))
n2 = float(num2.strip().replace('$', '').replace(',', ''))
print('Sum:', n1 + n2)
Sum: 3501.0
 

Recap: What We Learned#

  • Cleaning up text is often the first step in any project.
  • strip, replace, and translate are great for removing mess.
  • Convert to int or float safely, so you can use your data.
  • Watch out for tricky cases like errors and symbols.

With these basics, you can handle a lot of real-world text!

Thanks for Learning with Us!#

If you liked this lesson, hit Like, leave a comment, and subscribe to support more beginner Python videos.

Share the video with friends who want to build their coding skills!

See you next time!

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.