Python Strings

What Is a String?

A string is a sequence of characters enclosed in quotes. You can use 'single' or "double" quotes:

name = "Alice"
message = 'Hello'

Accessing Characters

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 Strings

Slicing lets you extract parts of a string:

text = "Python Programming"
print(text[0:6])   # 'Python'
print(text[7:])    # 'Programming'

Common String Methods

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: hello

Below are interactive prompts for common string methods. Try to write code that matches the target output.

Method: lower()

🔹 Prompt: Convert the string "HELLO WORLD" to all lowercase.

🎯 Target Output: hello world

Loading...
Output:

Method: upper()

🔹 Prompt: Convert the string "good morning" to all uppercase.

🎯 Target Output: GOOD MORNING

Loading...
Output:

Method: strip()

🔹 Prompt: Remove the extra spaces from the string " clean me ".

🎯 Target Output: clean me

Loading...
Output:

Method: replace()

🔹 Prompt: Replace the word "bad" with "good" in "This is bad."

🎯 Target Output: This is good.

Loading...
Output:

Method: split()

🔹 Prompt: Split the string "apple,banana,cherry" into a list using commas.

🎯 Target Output: ['apple', 'banana', 'cherry']

Loading...
Output:

Method: join()

🔹 Prompt: Join the list ["Python", "is", "fun"] into a sentence with spaces.

🎯 Target Output: Python is fun

Loading...
Output:

String Formatting

There are three common ways to format strings:

name = "Alice"
print(f"Hi, {name}!")
print("Hi, {}".format(name))
print("Hi, %s" % name)

Escape Characters in Strings

Escape characters let you insert special characters into strings using a backslash \.

Example: Use a single quote inside a string

Loading...
Output:

Example: Add a new line

Loading...
Output:

Example: Add a tab between words

Loading...
Output:

Example: Insert a backslash in a file path

Loading...
Output:

Example: Use ASCII values with \\x

Loading...
Output:

7. String Immutability

Strings can't be changed after they're created:

text = "cat"
text = text.replace("c", "b")
print(text)  # "bat"

8. Real-World Example

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.com

Practice Question

What will this output?

Loading...
Output:

Hint: It uses strip(), upper(), and replace().

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic