Cleaning text data
In the video, you saw how to build a custom function that performs a calculation and rounds the results. However, custom functions can be used for any task we expect to repeat! One common example is cleaning text data so that it conforms to specific requirements.
In this exercise, you'll create a function that takes string data and:
- Replaces spaces with underscores
- Converts to lowercase
- Returns the formatted string
This exercise is part of the course
Intermediate Python for Developers
Exercise instructions
- Define a function called
clean_string
, which takes an argument calledtext
. - Inside the function, create a variable called
no_spaces
, which contains thetext
with spaces replaced by underscores. - Inside the function, create a variable called
clean_text
, which converts characters inno_spaces
to lowercase. - Finish the function by producing
clean_text
as an output.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Create the clean_string function
____ ____(____):
# Replace spaces with underscores
____ = ____.____("____", "____")
# Convert to lowercase
____ = ____.____()
# Return the final text as an output
____ ____
converted_text = clean_string("I LoVe dATaCamP!")
print(converted_text)