Given a string and an index i, remove the character at the i-th position and return the resulting string. For Example:
Input: "PythonProgramming", i = 6
Output: "Pythonrogramming"
Let's explore different methods to do this task.
Using String Slicing
This method removes the i-th character by directly taking parts of the string before and after the character and joining them together. It is fast and memory-efficient.
s = "PythonProgramming"
i = 6
res = s[:i] + s[i+1:]
print(res)
Output
Pythonrogramming
Explanation:
- s[:i]: Extracts characters from the start up to (but not including) index i.
- s[i+1:]: Extracts characters from index i+1 to the end.
- '+': Concatenates the two slices, skipping the i-th character.
Using join() with List Comprehension
This method creates a new string by iterating over all characters and joining only those that are not at the i-th index.
s = "PythonProgramming"
i = 6
res = ''.join([s[j] for j in range(len(s)) if j != i])
print(res)
Output
Pythonrogramming
Explanation:
- [s[j] for j in range(len(s)) if j != i]: Iterates through all indices and skips the i-th character.
- ''.join(...): Converts the list of characters back into a string.
Using replace() with Slicing
This method removes the i-th character by replacing its first occurrence with an empty string.
s = "PythonProgramming"
i = 6
res = s[:i] + s[i:].replace(s[i], '', 1)
print(res)
Output
Pythonrogramming
Explanation: s[:i] + s[i:].replace(s[i], '', 1): Removes the i-th character by joining the part before i with the remaining substring after deleting s[i].
Using a For Loop
The for loop iterates over each character in the string and adds it to a new string only if it is not at the i-th position.
s = "PythonProgramming"
i = 6
res = ''
for j in range(len(s)):
if j != i:
res += s[j]
print(res)
Output
Pythonrogramming
Explanation:
- for j in range(len(s)) with if j != i: Loop through all indices, skipping the i-th.
- res += s[j]: Concatenate characters to res one by one.