Python Tutorial (33) - Example: Remove characters at a specified position in a string

Time: Column:Python views:256

Remove a Character from a Specified Position in a String

In this section, we will define a string and remove a character at a specified position.

Example

test_str = "PMEve"

We will remove the third character, 'n', from the string.

Code Example:

test_str = "PMEve"

# Output the original string
print("The original string is: " + test_str)

# Removing the third character 'n'
new_str = ""

for i in range(0, len(test_str)):
    if i != 2:
        new_str = new_str + test_str[i]

print("The string after removing the character is: " + new_str)

Output:

The original string is: PMEve
The string after removing the character is: PMEve

In this example, we iterate through each character of the string, skipping the one at the specified position (index 2), and build a new string without that character.