How to Remove Character from String Python By Index

In this Python tutorial, I will show you how to remove characters from a string Python by index.

As a data engineer or analyst, you must know how to process the dataset; one crucial task is to clean the dataset from unwanted noise.

Sometimes, you need to clean the dataset of unnecessary characters; for that, I have explained some methods, such as slicing, that you can use in this tutorial. I have used this method many times in my NLP project.

Let’s start

Remove Character from String Python By Index

What does removing a character from a string based on the index mean? It means deleting a specific character from the string by identifying its location within the string.

In Python, the string is considered an array or collection of characters in a sequence; each character has a position in the array, which can be accessed through the index.

The index starts from 0, so the index of the first character in the array is 0, the index of the second character is 1, and so on for other characters. Using the index, you can remove the character from the specific position in the string.

Using this indexing concept, I will show you how to remove a character from a string in Python using different methods.

Python Remove Character From String By Index Using Slicing

Slicing is a concept in Python that allows you to extract a specific part of a sequence, such as a tuple, list, etc. For example, you can apply slicing here if you have a list like [3, 4, 5 6] and want to extract or sequence [4, 5].

Before removing characters from the string, I will introduce you to slicing.

The syntax for implementing slicing is given below.

squence_name[start:stop:step]

Where,

  • sequence_name: It can be a list, tuple, string or any object on which the slicing technique can be applied.
  • [start: stop: step]: within square brackets[ ], the following things are:
    • The start is the index of the slice from which index slicing should begin; if you don’t specify the start, then it starts from the beginning by default.
    • Stop is the slice’s ending index, which means the index to which the slicing should stop.
    • The step is the size or increment between indices.
READ:  How to remove the first element from a list in Python

Let’s understand with an example,

Suppose you have a list of letters like [‘A’, ‘B’, ‘C’, ‘D’, ‘E’]. If you want to extract elements from index 1 to 4, you can do this by slicing, as shown below.

list_letters = ['A', 'B', 'C', 'D', 'E']

sliced_letters = list_letters[1:5]

print(sliced_letters)
Slicing Concepts Remove index From String Python

Look at the output. This line of code, list_letters[1:5], extracted the part of the list_letter from index 1 and to 5, returning [‘B’, ‘C’, ‘D’, ‘E’]. Want to know more about how slicing works? Read this tutorial, Indexing And Slicing In Python – Python Guides.

Now you understand how slicing works. To delete a character from a string python by index, you have to apply the logic of slicing the string into two parts, before the character that you want to remove and after the character.

For example, suppose you have a country named “Unitedd States” with a typo in words like twice the character ‘dd’, so you must remove this character. For that, you can use the slicing as shown below.

country_name = "Unitedd States"
fixed_country_name = country_name[:5] + country_name[6:]
print(fixed_country_name)
Python Remove Character From String By Index using Slicing

Look at the above output; it successfully removes the character ‘d’ from the “Unitedd States” string.

Understand this part of the code ‘country_name[:5] + country_name[6:]’. Here, this part, country_name[:5], extracts the string from index 0 to 5, and the next part, country_name[6:], extracts all letters from the 6th index to the end index. Then, both extracted parts are combined using the operation ‘+’.

As a result, it returns ‘United States’. This is how to remove characters from a string in Python by index.

Python Remove Character From String By Index Using For Loop

You can use the for loop to iterate over the string and then remove the character at the specified index.

READ:  How to Use Django Built-In Login System

Let me show you how to do that. For example, you have a product code as a string like ‘DC-3455-K’, but this code contains a duplicate character, 5. To remove this character, follow the below steps.

Create a string product_code and variable fixed_product_code =”” containing an empty string as shown below.

product_code = 'DC-3455-K'

fixed_product_code =''

As the character is at the index 5, you can run the for loop as shown below.

for i in range(len(product_code)):
   if i != 6:
       fixed_product_code += product_code[i]

print(fixed_product_code)
Python Remove Character From String By Index Using For Loop

Look in the putout removed the character ‘5’ at the index 6th. Let’s understand the code parts ‘for I in range(len(product_code))’; this line starts a loop and iterates over each index of the string ‘product_code’.

For each iteration, it takes index ‘i’ and checks if it is not equal to 6 to remove the characters at index 6 using ‘if i != 6’. If it is not equal to index 6, then it takes a character at that index ‘i’ and adds it to the empty string using the fixed_product_code += product_code[i].

Finally, it prints the string with removed characters using the ‘print(fixed_product_code)’; thus, it outputs ‘DC-345-K’.

This is how you can use the for loop to remove elements from string python.

Remove ith Character From String Python

To remove the ith character from a string in Python, you can use the replace() function. This function is designed to replace occurrences of a substring within a string.

To use it for our purpose. You should know the following things:

  • Identify the character at the given index.
  • Replace the first occurrence of that character with an empty string.

When replacing a single character with a new character in Python, use the replace() method. With this method, you can replace the character at the i index for the empty substring provided as (“).

READ:  Fibonacci series in Python [Complete program with 13 different examples]

The syntax for using the replace() function is given below.

string.replace(old,  new, count)

Where,

  • string: It is the original string on which the replace function is called to replace occurrences of substring.
  • old: This parameter defines the string that will be replaced.
  • new: Replace the existing value with a new one (a character or a string).
  • count: An integer value that indicates how many instances of the old character or substring we want to replace with the new one. It is an optional parameter.

For example, you have the string “Unitedd States.” To remove the character ‘d’ at index 6, create a function named ‘remove_character’, as shown below.

def remove_character(string, index):

    for i in range(len(string)):
        if i==index:
            final_string=string.replace(string[index],"",1)
    return final_string

Call the function using the string “Unitedd States” and index 6, as shown below.

print(remove_character("Unitedd States",6))
Remove ith Character From String Python

Look at the output; it removes the character at index 6, which is ‘d’ from the “Unitedd States” string, and returns the correct country name, which is the United States, that you can see in the output.

From the above methods, I hope that you understand how to remove specific characters from the string in Python.

Conclusion

In this Python tutorial, you learned how to remove characters from a string Python by index.

You learned the methods of slicing for loop and used the custom function to remove the character from the index.

You may like to read: