Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

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.

IntermediatePhase 5 - Category 4: String TransformationExample 3 of 10
insert-character-at-position.py
1# Take string input
2s = input("Enter a string: ")
3char = input("Enter character to insert: ")
4pos = int(input("Enter position: "))
5
6# Insert
7if 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. 1

    Require pos from zero through len(s).

  2. 2

    Concatenate prefix, inserted text, and suffix.

  3. 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.