Remove All Special Characters From String Python
Last Updated : Jan 1, 2023
IN - Python
In this tutorial we will show you the solution of remove all special characters from string python, there are many ways to remove special characters from a string, not only from the beginning or end but anywhere in the string.
We will show You the easiest way to remove all special characters from string python.
Also this way to remove special characters has the least learning curve because of only one concept to understand. And that is the replace() method.
Python string method replace() replaces the undesired character with the desired character.
Step By Step Guide On Remove All Special Characters From String Python :-
st1='$@!@#$%Univ**er+s.i09ty2' removal_chars = '$!@#%*+092.' def st_cleaner(st): for c in removal_chars: st=st.replace(c,'') print(st) st_cleaner(st1)
- We will use VS Code for this example demonstration.
- Firstly, we declare a string variable st1 to hold our raw string full of special characters here and there. We will clean this string completely.
- Python variables are dynamic and assume variable types automatically upon data assignment.
- Our first work now is to identify the string we want to be the result. This indirectly also asks us to identify the characters we don’t want to be in the result, i.e they need to be removed.
- So we identify such characters to be removed and form a string pack of such characters in a variable called removal_chars.
- We now define a function called st_cleaner() to remove all such special characters from the string. This function takes a string as an argument.
- A for loop is used to iteratively identify and replace characters with null, in each step and assign the modified string back to the string variable which we passed as the function argument.
- For e.g in first iteration of for loop, c=’$’. The replace() method works as replace(‘$’,’’). Thus, anywhere in the string where $ is encountered, it will be replaced by ‘’, i.e $Ca$r will appear as Car.
- This modified string ( st.replace() ) worked upon by replace() with dot (.) operator is assigned back to st and in the next iteration, this modified string is worked upon. (Note that $ has been completely removed now. Remaining characters will be removed in the same way).
- In this way iteratively, all special characters are removed and the string is printed. This sums up the function.
- Now we can call the function with our desired string st1 and get the result. You can play with the function as You like.
I hope this tutorial on remove all special characters from string python helps you and the steps and method mentioned above are easy to follow and implement.