Remove character at a specific index in a Python string
This post will discuss how to remove a character at the specific index in Python String.
To remove any character from the String, you have to create a new string since strings are immutable in Python. There are several ways to do so, which are discussed below in detail:
1. Using Slicing
The most common approach to removing a character from a string at the specific index is using slicing. Here’s a simple example that returns the new string with character at given index i removed from the string s.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': s = "ABCDE" i = 2 s = s[:i] + s[i+1:] print(s) # ABDE |
2. Using Generator Expression
Another option is to use generators to filter the characters in the string and then join them back again to construct a new string:
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': s = "ABCDE" i = 2 s = ''.join(s[x] for x in range(len(s)) if x != i) print(s) # ABDE |
3. Converting to list
Another plausible way is to convert your string into a mutable list of characters. Then you can convert the list back to a string after removing the character at the specified index.
|
1 2 3 4 5 6 7 8 9 10 11 |
if __name__ == '__main__': s = "ABCDE" i = 2 l = list(s) del(l[i]) s = "".join(l) print(s) # ABDE |
That’s all about removing the character at a specific index in a string in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)