Insert Character at Position
Insert text at a validated string position using slices. Students join prefix, inserted text, and suffix and include the position just after the character.
1# Take string input2s = input("Enter a string: ")3char = input("Enter character to insert: ")4pos = int(input("Enter position: "))56# Insert7if 0 <= pos <= len(s):8 result = s[:pos] + char + s[pos:]9 print(f"After insertion: {result}")10else:11 print("Invalid position")
Output
Enter a string: Hello Enter character to insert: X Enter position: 2 After insertion: HeXllo
In this one
- Split at an insertion boundary
- Validate endpoint-inclusive positions
- Rebuild text from three pieces
How it works
- 1
Require pos from zero through len(s).
- 2
Concatenate prefix, inserted text, and suffix.
- 3
Print the result or invalid-position feedback.
Edge cases
Can insertion occur at len(s)?
Can insertion occur at len(s)?
Yes. That appends after the last character.
Can pos be negative?
Can pos be negative?
Not in this program; the guard rejects it.
What's going on
A valid insertion position ranges from zero through len(s), including both endpoints. The code joins s[:pos], char, and s[pos:].
The slices divide the original without losing a character. Position zero inserts at the front; position len(s) appends at the end. The inserted response may contain several characters because the code validates position but not inserted-text length.
Can insertion occur at len(s)? Yes. That appends after the last character.
Can pos be negative? Not in this program; the guard rejects it.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why use both slices?
Pick an answer to check it.
Question 2
Can insertion occur at len(s)?
Pick an answer to check it.
Questions people ask
Can insertion occur at len(s)?
Yes. That appends after the last character.
Can pos be negative?
Not in this program; the guard rejects it.
Why use both slices?
To retain the text before and after the insertion point.
๐Related Content
- ๐
Phase 5 - Learn Concepts
Review Phase 5 concepts and explanations
- ๐
Phase 5 - Quiz
Test your Phase 5 understanding with quiz questions
- ๐ป
Phase 5 - All Practice Problems
Explore all practice problems for Phase 5
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum