String Operations
A string is a sequence of characters that stores text, such as names, messages, or categories.
In data analysis, you often use strings to clean data, combine pieces of text, or transform it into a useful format.
Combining Strings
You can join two or more strings using the +
operator:
first_name = "Emily" last_name = "Clark" full_name = first_name + " " + last_name print("Full Name:", full_name)
This combines the first and last names into one string, with a space in between.
Changing Case
You can change the case of a string using the upper()
and capitalize()
methods:
greeting = "hello world" print(greeting.upper()) # HELLO WORLD print(greeting.capitalize()) # Hello world
upper()
makes all letters uppercase. capitalize()
makes only the first letter uppercase.
Removing Extra Spaces
Users often type extra spaces accidentally. You can clean them using the strip()
method:
raw_input = " data science " clean_input = raw_input.strip() print("Cleaned:", clean_input)
This removes spaces at the start and end of the string, which is useful for cleaning form inputs.
Replacing Text
If a string contains outdated or incorrect terms, you can replace them using the replace()
method:
message = "I love Java" updated_message = message.replace("Java", "Python") print(updated_message)
This finds "Java"
in the text and replaces it with "Python"
.
Which Python function would you use to remove extra spaces from the beginning and end of a string?
replace()
upper()
strip()
capitalize()
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result