Python remove characters from string; Through this tutorial, i am going to show you how to remove first, last, and specific characters from string in python.
Python remove a character from a string
- To remove a last character from a string in python
- To remove first character from a string in python
- To remove multiple characters or n characters from string in python.
- How to remove specific characters from a string python
To remove a last character from a string in python
See the following python program to remove a last character from a string in python;
# Python code to remove last character from string #take input string from user str = input("Please Enter String : ") # Remove last character str = str[:-1] # Print remaining string print(str)
After executing the above program, the output will be:
Please Enter String : my world.... Result :- my world...
To remove first character from a string in python
See the following python program to remove a first character from a string in python;
# Python code to remove first character from string # initializing test string str='!my world' # Remove first character str = str[1:] # Print remaining str print(str)
After executing the above program, the output will be:
Please Enter String : A programmer Result :- programmer
To remove multiple characters or n characters from a string python
See the following python program to remove multiple characters or n characters from a string;
# Python code to remove multiple characters from string #take input string from user str = input("Please Enter String : ") removeChr = input("Please Enter Multiple Character, which you want to remove : ") # Remove multiple characters new_string = str for character in removeChr: new_string = new_string.replace(character, "") # Print remaining string print('Result :- ', new_string)
After executing the above program, the output will be:
Please Enter String : !(Hell@o) Please Enter Multiple Character, which you want to remove : !()@ Result :- Hello
How to remove specific characters from a string python
See the following python program to remove specific characters or specific index characters from a string;
# Python code to remove specific index character from string #take input string from user str = input("Please Enter String : ") n = int(input("Please Enter Index of Character, which you want to remove : ")) # Remove nth character x = str[:n] # up to but not including n y = str[n + 1:] # n+1 till the end of string str = x + y # Print remaining string print('Result :- ', str)
After executing the above program, the output will be:
Execution -1
Please Enter String : python Please Enter Index of Character, which you want to remove : 0 Result :- ython
Execution -2
Please Enter String : python Please Enter Index of Character, which you want to remove : 1 Result :- pthon