Course Content
How to Add a Virtual Environment in Python
0/1
Set
0/1
Python
About Lesson

What is Indexing?

Indexing refers to accessing a particular character of a string using its position or index. Python strings are indexed starting from 0 for the first character, 1 for the second, and so on.

  • Positive Indexing: Starts from the beginning of the string.
  • Negative Indexing: Starts from the end of the string. -1 refers to the last character, -2 refers to the second-to-last character, and so on.

Syntax: string[index]

Example: Positive-indexing

Python
str1 = "Python"
print(str1[0])  # 'P'
print(str1[1])  # 'y'
print(str1[2])  # 't'

Example: Negative-indexing

Python
string1 = "Python"
print(string1[-1])  # 'n' (last character)
print(string1[-2])  # 'o' (second to last character)
print(string1[-6])  # 'P' (first character, same as text[0])

What is Slicing?

Slicing allows you to extract a sub-string (or portion of the string) by specifying a start index, end index, and an optional step value. Slicing can be used to create a new string from the original string without modifying it, since strings in Python are immutable.

Syntax: string[start:end:step]

  • start: The index where the slice starts (inclusive).
  • end: The index where the slice ends (exclusive). The character at the end index is not included.
  • step: The step size between indices (optional). If omitted, it defaults to 1.

In Python, if no start is specified, slicing begins from the beginning of the string, and if no end is provided, it slices until the last character. If no step is given, it defaults to 1, slicing characters one by one. Negative indices allow slicing from the end of the string.

Example:

Python
text = "Python"

# Extracting characters from index 1 to index 4 (end is exclusive)
print(text[1:4])  # "yth" (characters at index 1, 2, and 3)

# Extracting from the start to index 3 (end is exclusive)
print(text[:3])   # "Pyt"

# Extracting from index 2 to the end of the string
print(text[2:])   # "thon"

# Extracting the whole string
print(text[:])    # "Python"

Slicing with Negative Indices

Python
text = "Python"

# Extracting the last character (negative index -1)
print(text[-1])  # "n"

# Slicing the last 3 characters (index -3 to -1)
print(text[-3:])  # "hon"

# Extracting the substring "yth" from the middle using negative indices
print(text[-5:-2])  # "yth"

Using the step Parameter in Slicing

You can also specify a step value in slicing, which will determine how many steps the slice should skip between indices.

Python
text = "Python"

# Extract every second character (step = 2)
print(text[::2])  # "Pto" (characters at indices 0, 2, and 4)

# Extract the string in reverse order (step = -1)
print(text[::-1])  # "nohtyP"

# Extract characters from index 1 to 5, with a step of 2
print(text[1:5:2])  # "yhn"