Skip to main content
Practice

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:

Combining Strings
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:

Changing Case
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:

Removing Extra Spaces
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:

Replacing Text
message = "I love Java"
updated_message = message.replace("Java", "Python")
print(updated_message)

This finds "Java" in the text and replaces it with "Python".

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.