Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Accessing Values of Strings in Python
Python does not support a character type; these are treated as strings of length one, thus also considered a substring. To access individual characters or substrings, use square brackets with the index or slice notation.
Accessing Individual Characters
Use square brackets with an index to access a single character. Python uses zero-based indexing ?
var1 = 'Hello World!'
var2 = "Python Programming"
print("var1[0]:", var1[0])
print("var1[6]:", var1[6])
print("var2[0]:", var2[0])
print("var2[-1]:", var2[-1]) # Last character
var1[0]: H var1[6]: W var2[0]: P var2[-1]: g
Accessing Substrings with Slicing
Use slice notation [start:end] to extract a portion of the string. The end index is exclusive ?
var1 = 'Hello World!'
var2 = "Python Programming"
print("var2[1:5]:", var2[1:5])
print("var1[0:5]:", var1[0:5])
print("var2[7:]:", var2[7:]) # From index 7 to end
print("var1[:5]:", var1[:5]) # From start to index 4
var2[1:5]: ytho var1[0:5]: Hello var2[7:]: Programming var1[:5]: Hello
Advanced Slicing with Step
Add a step parameter to control the increment between characters ?
text = "Python Programming"
print("Every 2nd character:", text[::2])
print("Reverse string:", text[::-1])
print("Characters 1-10 with step 2:", text[1:10:2])
Every 2nd character: Pto rgamn Reverse string: gnimmargorP nohtyP Characters 1-10 with step 2: yhno
Key Points
| Syntax | Description | Example |
|---|---|---|
string[index] |
Single character |
"Hello"[0] ? 'H' |
string[start:end] |
Substring slice |
"Hello"[1:4] ? 'ell' |
string[::-1] |
Reverse string |
"Hello"[::-1] ? 'olleH' |
string[-1] |
Last character |
"Hello"[-1] ? 'o' |
Conclusion
String indexing and slicing are fundamental operations in Python. Use single indices for characters and slice notation for substrings. Remember that Python uses zero-based indexing and negative indices count from the end.
