A string is a sequence of characters enclosed in quotes. You can use 'single' or "double" quotes:
name = "Alice"
message = 'Hello'In Python, strings are sequences of characters, and each character has a position called an index. You can use indexing to retrieve a specific character from a string.
Indexing starts from 0 for the first character, 1 for the second, and so on. You can also use negative indices to access characters from the end of the string: -1 is the last character, -2 is the second last, etc.
Examples:
text = "Python"
print(text[0]) # 'P' (first character)
print(text[1]) # 'y' (second character)
print(text[-1]) # 'n' (last character)
print(text[-2]) # 'o' (second last character)Slicing lets you extract parts of a string:
text = "Python Programming"
print(text[0:6]) # 'Python'
print(text[7:]) # 'Programming'In Python, string methods are functions that you can call on string variables to modify or inspect them. You call a method using dot notation: string_variable.method(). For example:
greeting = "HELLO"
print(greeting.lower()) # Output: helloBelow are interactive prompts for common string methods. Try to write code that matches the target output.
lower()🔹 Prompt: Convert the string "HELLO WORLD" to all lowercase.
🎯 Target Output: hello world
upper()🔹 Prompt: Convert the string "good morning" to all uppercase.
🎯 Target Output: GOOD MORNING
strip()🔹 Prompt: Remove the extra spaces from the string " clean me ".
🎯 Target Output: clean me
replace()🔹 Prompt: Replace the word "bad" with "good" in "This is bad."
🎯 Target Output: This is good.
split()🔹 Prompt: Split the string "apple,banana,cherry" into a list using commas.
🎯 Target Output: ['apple', 'banana', 'cherry']
join()🔹 Prompt: Join the list ["Python", "is", "fun"] into a sentence with spaces.
🎯 Target Output: Python is fun
There are three common ways to format strings:
name = "Alice"
print(f"Hi, {name}!")
print("Hi, {}".format(name))
print("Hi, %s" % name)Escape characters let you insert special characters into strings using a backslash \.
Strings can't be changed after they're created:
text = "cat"
text = text.replace("c", "b")
print(text) # "bat"Cleaning and parsing strings is common in web apps, data science, and file handling:
email = " USER@Example.COM "
cleaned = email.strip().lower()
print(cleaned) # user@example.comWhat will this output?
Hint: It uses strip(), upper(), and replace().
Ask the AI if you need help understanding or want to dive deeper in any topic