Python program for removing i-th character from a string
Last Updated :
10 Nov, 2024
Improve
In this article, we will explore different methods for removing the i-th character from a string in Python. The simplest method involves using string slicing.
Using String Slicing
String slicing allows us to create a substring by specifying the start and end index. Here, we use two slices to exclude the i-th character.
s = "PythonProgramming"
# Index of the character to remove
i = 6
# Removing i-th character
res = s[:i] + s[i+1:]
print(res)
Output
Pythonrogramming
Explanation:
- s[:i]: This slice takes all characters from the start of the string up to, but not including, the i-th index.
- s[i+1:]: This slice takes all characters starting from the index after i to the end of the string.
- Combining these slices using + effectively removes the character at the specified index.
Let’s explore other different methods to removing i-th character from a string:
Table of Content
Using a for Loop
A basic for loop can also be used to iterate over each character in the string and build a new string that excludes the i-th character.
s = "PythonProgramming"
# Index of character to remove
i = 6
# Initialize an empty string to store result
res = ''
# Loop through each character in original string
for j in range(len(s)):
# Check if current index is not index to remove
if j != i:
# Add current character to result string
res += s[j]
print(res)
Output
Pythonrogramming
Using join() with List Comprehension
Another way to remove the i-th character from a string is by using join() and a list comprehension. The idea of approach is similar to the above loop method.
s = "PythonProgramming"
# Index of the character to remove
i = 6
# Removing i-th character using list comprehension
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]: This list comprehension iterates over each character in s, including only those that are not at the i-th index.
- ”.join(…): The join() function concatenates the list of characters into a single string, effectively skipping the i-th character.