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
How to print characters from a string starting from 3rd to 5th in Python?
Python strings use indexing to access individual characters, starting from index 0. To extract characters from the 3rd to 5th position, we can use string slicing with different approaches.
String Indexing Basics
In Python, string indexing starts from 0. For example, the string "Coding" has indices 0,1,2,3,4,5 for characters C,o,d,i,n,g respectively.
text = "Coding"
print(f"Length: {len(text)}")
print(f"First character (index 0): {text[0]}")
print(f"Third character (index 2): {text[2]}")
Length: 6 First character (index 0): C Third character (index 2): d
Method 1: Using String Slicing
String slicing uses the syntax string[start:end] where start is inclusive and end is exclusive ?
# Extract 3rd to 5th characters (indices 2 to 4)
text = "TutorialsPoint"
result = text[2:5]
print(f"Original string: {text}")
print(f"Characters 3rd to 5th: {result}")
Original string: TutorialsPoint Characters 3rd to 5th: tor
Method 2: Using Negative Indexing
Negative indexing starts from -1 (last character) and counts backward ?
text = "Tutorials"
# Calculate negative indices for 3rd to 5th positions
result = text[-7:-4] # -7 is 3rd position, -4 excludes 6th position
print(f"Original string: {text}")
print(f"Using negative indexing: {result}")
Original string: Tutorials Using negative indexing: tor
Method 3: Using Conditional Check
Add validation to handle strings shorter than 5 characters ?
def extract_3rd_to_5th(text):
if len(text) >= 5:
return text[2:5]
else:
return "String too short"
# Test with different strings
strings = ["TutorialsPoint", "Code", "Programming"]
for s in strings:
result = extract_3rd_to_5th(s)
print(f"'{s}' ? '{result}'")
'TutorialsPoint' ? 'tor' 'Code' ? 'String too short' 'Programming' ? 'ogr'
Comparison of Methods
| Method | Syntax | Best For |
|---|---|---|
| Basic Slicing | text[2:5] |
Simple, direct extraction |
| Negative Indexing | text[-7:-4] |
When counting from end |
| With Validation | if len(text) >= 5 |
Handling variable string lengths |
Conclusion
Use basic string slicing [2:5] for extracting 3rd to 5th characters. Add length validation when working with variable-length strings to avoid index errors.
