📝 Manipulating Text
Welcome to Module 3! Text is everywhere in AI – from user commands and chatbot responses to articles we analyze (Natural Language Processing) and labels for data. Python makes it easy to manipulate text data, called strings.
In this module, we'll learn how to join strings together, repeat them, find out how long they are, and pick out specific characters. Let's dive in!
🔗 Combining & Repeating Strings
Two common ways to build new strings from existing ones.
Concatenation (+)
Joining strings end-to-end using the plus sign.
"AI" + " " + "Rules"
➡️
"AI Rules"
Multiplication (*)
Repeating a string a certain number of times.
"Go! " * 3
➡️
"Go! Go! Go! "
These operators let us dynamically construct text messages, separators, and more.
📏 Measuring & Accessing Characters
Finding the length and getting individual characters.
Finding Length (len())
The built-in len()
function tells you how many characters are in a string (including spaces).
len("Hello AI")
➡️ 8
Accessing Characters (Indexing [])
Use square brackets []
with a number (the index) to get the character at that position. Important: Indexing starts from 0!
model = "GPT-4"
model[0]
➡️ 'G'
(First character)model[2]
➡️ 'T'
(Third character)Knowing the length and accessing specific parts is crucial for analyzing and processing text.
⚙️ Text Operations in Action
Let's combine these concepts to work with an AI-related message.
We start with two strings, `prefix` and `core_message`.
The +Joins strings together (Concatenation). Remember to add spaces if needed! operator combines them with a space in between to create `full_status`.
The *Repeats a string a specified number of times. operator creates a `separator` line by repeating the "=" string.
len()Returns the number of characters in the string passed to it. calculates the total characters in `full_status`.
[]Accesses a character at a specific position (index). Starts from 0! `[0]` gets the very first character. is used with index `0` to get the first character ('D') from `core_message`.
🧠 Quick Check!
Module 3 Theory Complete!
Fantastic! You now know the basics of manipulating strings in Python. This is fundamental for any AI task involving text.
Time to practice these skills! Head to the Practice Zone or the Advanced Practice for Module 3.