String Manipulation & Indexing

Strings are fundamental for working with text in Python. Understanding indexing and slicing is crucial for text processing and manipulation.

What are Strings?

message = "Python"
print(len(message)) # → 6
6
Strings are immutable sequences of Unicode characters. They can be:
  • Indexed: message[0] → 'P'
  • Sliced: message[2:5] → 'tho'
  • Concatenated: "Py" + "thon"

Indexing Characters

word = "Elephant"
print(word[0]) # → E
print(word[3]) # → p
E
p

In this example:

  • Indexes start at 0 for first character
  • word[3] accesses 4th character
  • Indexes beyond length cause IndexError

Reverse Access

city = "Paris"
print(city[-1]) # → s
print(city[-3]) # → i
s
i

Negative indexes count from the end:

  • -1 → Last character
  • -2 → Second last

String Slicing

phrase = "Hello World"
print(phrase[0:5]) # → Hello
print(phrase[6:11]) # → World
Hello
World

Slice syntax: [start:end:step]
End index is exclusive. Omit start/end for defaults.

Practical Use: Usernames

email = "user.name@domain.com"
username = email[:email.index("@")]
print(f"Username: {username}")
Username: user.name

Your Task: Character Extraction

Given text = "hello":

  1. Store first character in first
  2. Store last character in last
  3. Use indexing (both positive and negative)

Final output should be: First: h, Last: o

Section 1/6What are Strings?

What are Strings?

Explore this concept

String Manipulation & Indexing

Strings are fundamental for working with text in Python. Understanding indexing and slicing is crucial for text processing and manipulation.

What are Strings?

message = "Python"
print(len(message)) # → 6
6
Strings are immutable sequences of Unicode characters. They can be:
  • Indexed: message[0] → 'P'
  • Sliced: message[2:5] → 'tho'
  • Concatenated: "Py" + "thon"

Output:

Click "Check" to run your code.