Ways to remove i’th character from string in Python
In Python it is all known that string is immutable and hence sometimes poses visible restrictions while coding the constructs that are required in day-day programming. This article presents one such problem of removing i’th character from string and talks about possible solutions that can be employed in achieving them.
In this method, one just has to run a loop and append the characters as they come and build a new string from the existing one except when the index is i.
Code #1 : Demonstrating Naive method to remove i’th char from string.
Output:
The original string is : GeeksForGeeks The string after removal of i'th character : GeksForGeeks
Note: This solution is much slower (has O(n^2) time complexity) than the other methods. If speed is needed, method #3 is similar in logic and is faster (it has O(n) time complexity).
str.replace()
replace()
can possibly be used for performing the task of removal as we can replace the particular index with empty char, and hence solve the issue.
Drawback: The major drawback of this approach is that it fails in case there as duplicates in a string that match the char at pos. i. replace()
replaces all the occurrences of a particular character and hence would replace all the occurrences of all the characters at pos i. We can still sometimes use this function if the replacing character occurs 1st time in the string.
Code #2 : Demonstrating the use of str.replace()
to remove i’th char.
Output:
The original string is : GeeksForGeeks The string after removal of i'th character( doesn't work) : GksForGks The string after removal of i'th character(works) : GeekForGeeks
Once can use string slice and slice the string before the pos i, and slice after the pos i. Then using string concatenation of both, i’th character can appear to be deleted from the string.
Code #3 : Demonstrating the use of slice and concatenation to remove the i’th char.
Output :
The original string is : GeeksForGeeks The string after removal of i'th character : GeksForGeeks
str.join()
and list comprehensionIn this method, each element of string is first converted as each element of list, and then each of them is joined to form a string except the specified index.
Code #4 : Demonstrating str.join()
and list comprehension to remove i’th index char.
Output :
The original string is : GeeksForGeeks The string after removal of i'th character : GeksForGeeks
No comments:
Post a Comment
Your feedback is highly appreciated and will help us to improve our content.