This article describes two common methods that you can use to remove characters from a string using Python:
String replace()
methodString translate()
methodTo learn some different ways to remove spaces from a string in Python, refer to Remove Spaces from a String in Python.
A Python String object is immutable, so you can’t change its value. Any method that manipulates a string value returns a new String object.
The examples in this tutorial use the Python interactive console in the command line to demonstrate different methods that remove characters.
Deploy your Python applications from GitHub using DigitalOcean App Platform. Let DigitalOcean focus on scaling your app.
replace()
MethodThe String replace() method replaces a character with a new character. You can remove a character from a string by providing the character(s) to replace as the first argument and an empty string as the second argument.
Declare the string variable:
- s = 'abc12321cba'
Replace the character with an empty string:
- print(s.replace('a', ''))
The output is:
Outputbc12321cb
The output shows that both occurrences of the character a
were removed from the string.
replace()
MethodDeclare a string variable with some newline characters:
- s = 'ab\ncd\nef'
Replace the newline character with an empty string:
- print(s.replace('\n', ''))
The output is:
Outputabcdef
The output shows that both newline characters (\n
) were removed from the string.
replace()
MethodThe replace()
method takes strings as arguments, so you can also replace a word in string.
Declare the string variable:
- s = 'Helloabc'
Replace a word with an empty string:
- print(s.replace('Hello', ''))
The output is:
Outputabc
The output shows that the string Hello
was removed from the input string.
replace()
MethodYou can pass a third argument in the replace()
method to specify the number of replacements to perform in the string before stopping. For example, if you specify 2
as the third argument, then only the first 2 occurrences of the given characters are replaced.
Declare the string variable:
- s = 'abababab'
Replace the first two occurrences of the character with the new character:
- print(s.replace('a', 'A', 2)) # perform replacement twice
The output is:
OutputAbAbabab
The output shows that the first two occurrences of the a
character were replaced by the A
character. Since the replacement was done only twice, the other occurrences of a
remain in the string.
translate()
MethodThe Python string translate()
method replaces each character in the string using the given mapping table or dictionary.
Declare a string variable:
- s = 'abc12321cba'
Get the Unicode code point value of a character and replace it with None
:
- print(s.translate({ord('b'): None}))
The output is:
Outputac12321ca
The output shows that both occurrences of the b
character were removed from the string as defined in the custom dictionary.
translate()
methodYou can replace multiple characters in a string using the translate()
method. The following example uses a custom dictionary, {ord(i): None for i in 'abc'}
, that replaces all occurrences of a
, b
, and c
in the given string with None
.
Declare the string variable:
- s = 'abc12321cba'
Replace all the characters abc
with None
:
- print(s.translate({ord(i): None for i in 'abc'}))
The output is:
Output12321
The output shows that all occurrences of a
, b
, and c
were removed from the string as defined in the custom dictionary.
translate()
MethodYou can replace newline characters in a string using the translate()
method. The following example uses a custom dictionary, {ord('\n'): None}
, that replaces all occurrences of \n
in the given string with None
.
Declare the string variable:
- s = 'ab\ncd\nef'
Replace all the \n
characters with None
:
- print(s.translate({ord('\n'): None}))
The output is:
Outputabcdef
The output shows that all occurrences of the newline character \n
were removed from the string as defined in the custom dictionary.
In this tutorial, you learned some of the methods you can use to remove characters from strings in Python. Continue your learning about Python strings.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Sign up for Infrastructure as a Newsletter.
Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
s=[‘#’,‘Mini Skirt’,‘Skirt’,‘Chiffon Top’,‘T-Shirt’,‘Classic’,‘Classical’,‘Essential’,‘Short-Sleeve’,‘shirt’,‘Top’,‘Premium’,‘leggings’,‘Classic’,‘Pullover’,‘Sweatshirt’,‘Hoodie’,‘Zipped’] finale =[] for i in range(0,len(TrendingApparelTexts2)):# length of your sentence string list processing = TrendingApparelTexts2[i] #storing each sentence to be compaired for j in range(0,len(s)): # iterating through the dictionary of words I don’t want in my sentences Delete = s[j] if Delete in processing: processing = processing.replace(Delete,‘’) finale.append(processing) print(finale)
- Affan Ahmed
Receive an input text from the user and print all letters except ‘e’ and ‘s’ by using for loop?
- Ranjith
# try this s=input(“Enter a string:\n”) delete=input(“enter string to delete\n”) position=s.find(delete) length_s=len(s) length_word=len(delete) s1=s[:position] s2=s[position+length_word+1::] s3=s1+s2 print(s3)
- Meena Vyas
How would I delete all characters bar the first character, without specifying the character: For example, I have a bunch of items: banana apple orange mango passion fruit guava Say I wanted the user to guess the word only given the first letter of each word (each WORD not each item, eg for passion fruit, the user is given 'p f ’ not just 'p ', how would I do that?
- …
Hi Pankaj. I have a problem in removing character from string. Actually, I don’t know why the following program is unable to remove character from second string. could you please help me? # Type your code here def anagrams(my_string1, my_string2): a=my_string1.lower() b=my_string2.lower() out_put=True if len(my_string1)!=len(my_string2): out_put= False else: for i in a: if i in b: a=a.strip(i) b=b.strip(i) out_put = True else: out_put=False return out_put print(anagrams(“Orchestaa”,“Carthorse”))
- zara
How can I remove I greater number of items? For example, if I wanted to remove 1000 characters you don’t necessarily want to type out and replace with some other string.
- Daniel H O’Hearn
How to remove backslash from a string?
- sundara rajan
I need to make a program that takes a sentence and outputs it without spaces. Can you help me?
- lallan
import pickle code1 = (“1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010”) l = list(code1) pickle.dump(code1, open(“code1”, “wb”)) print(“original list”) print(code1) Stuck here, how can i add/remove more numbers to this code? TIA
- A S
s=input(); n=int(input()); fs=fs.replace( …); print(fs)
- boopathi