Coders Packet

Remove n Special Characters from a String in Python

By Vijay Viswha

The following code is used to remove user-specified n special characters from a user-inputted string using loops and if conditions in Python.

Hello, the given code is used to remove user-specified n special characters from a user-inputted string using loops and if conditions in Python. We will be using one user-defined function, for loop and if, else statement to get the desired output. 

The code begins off with defining a function remove_chars. The function has two arguments, the user-inputted string (string_input) and the number of characters to be removed (n). After defining, under the function, we declare a list of all special characters as a string called 'special_chars'. We declare a variable 'count' as 0 and an empty result string as 'final_string'.

After declaring all necessary data, we write a for loop under the same function to inspect every character from the 0th index to the last index one by one. Then we write an if condition under the for loop to check whether the current character under inspection is present in the string 'special_chars' and if count is lesser than n. Note that both conditions are checked using one if condition. If both conditions are true then the overall condition is true according to 'and' statement and henceforth the count is incremented by 1. This means, the character under inspection is present in the list of special characters and the count is also lesser than the number of characters to be removed, therefore the condition is true.

If either one of the conditions is false then the current character is appended to the result string. Meaning, if the character under inspection is not a special character or the number of special characters to be removed has already been done then the program appends all the characters to the final string since there is no need for removal of anything. And finally, after the operation is repeated on each character of the 'string_input', the final string is returned.

Now we come out of the function to the main part of the program. Here we take two inputs, the user-inputted string as 'string_input' and number of characters to be removed as 'n'. After which, we call the function by passing both inputs as arguments using the print function, to print the function returned result string.

Now run the program, input the necessary details and output shall look something like this:

Test output of the given code

 

 

Download Complete Code

Comments

No comments yet

Download Packet

Reviews Report

Submitted by Vijay Viswha (viswha19123)

Download packets of source code on Coders Packet