String Indexing and Slicing
Python tutorial · PySpark.in
String Indexing and Slicing in Python
Strings in Python are indexed, meaning every character has a position starting from 0.
String Indexing
```
s = "PYTHON"
print(s[0]) # P
print(s[1]) # Y
print(s[5]) # N (last character)
```
Negative Indexing
Negative indices allow you to access characters from the end.
```
name = "PYSPARK"
print(name[-1]) # K
print(name[-2]) # R
print(name[-3]) # A
print(name[-4]) # P
print(name[-5]) # S
print(name[-6]) # Y
print(name[-7]) # P
```
What is String Slicing?
String slicing means extracting a part of the string (substring).
Syntax
string[start : end : step]
Meaning:
- start → starting index (inclusive)
- end → ending index (exclusive)
- step → skip count (optional)
Examples
```
name = "Pyspark"
print(name[0]) # P
print(name[0:2]) # Py
```
Negative Indices in Slicing
Negative indices allow slicing from the end.
```
name = "Hello"
print(name[2:-1]) # ll
```
Slicing with Step
The step value decides how many characters to skip.
```
name = "Hello01234"
print(name[0:10:1]) # Hello01234 (no skipping)
print(name[0:10:2]) # Hlo24 (skip 1 each time)
print(name[0:10:3]) # Hl13 (skip 2 each time)
```
Rule:
If step = n, Python skips n-1 characters each time.
Omitting Indices
If you don’t specify start or end, Python fills them automatically.
Expression | Equivalent To | Meaning |
|---|---|---|
name[:4] | name[0:4] | From start to index 3 |
name[1:] | name[1:len(name)] | From index 1 to end |
name[:] | name[0:len(name)] | Whole string |
Example:
```
name = "Hello01234"
print(name[:4]) # Hell
print(name[1:]) # ello01234
print(name[:]) # Hello01234
```
Important Notes
- Slicing works like range() → end index is excluded.
- Negative indices count from the end of the string.
- step allows skipping characters.
- Omitting start defaults to 0, and omitting end defaults to len(string).
More Python tutorials
- What is Python and Why is it used for Data Science and Data Engineering?
- How Does Python Work in the Backend? Internal Working of Python
- Top 30 Python Interview Questions for Data Science
- 3-Month Python Roadmap to Excel in Data Science and Machine Learning
- Python Data Types Explained – A Beginner’s Guide
- test
All tutorials · Try the free PySpark compiler · Practice challenges