Lecture

String Operations

A string is a sequence of characters used to store text — such as names, messages, or categories.

In data analysis, strings are often used to clean, combine, or transform text into a usable 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, while 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 beginning and end of the string — useful when cleaning user inputs or survey data.


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 searches for "Java" in the text and replaces it with "Python".

Quiz
0 / 1

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

Run
Generate

Execution Result