In this article, we are going to see different ways to remove characters from a string.
The string is an in-built class i.e. data type in python which is a sequence of characters, enclosed by double/single/triple inverted comma, an array of Unicode characters (i.e. you can have a string in any language in the world, not just English).
Strings in Python are immutable; once created you cannot change it. When you update the string, the interpreter creates a new string and the garbage collector removes the previous string if you haven't removed it. Unlike other programming languages, there’s no character data type in python.
A character can be a string of length 1. What you write inside an inverted comma is called a literal. As strings are immutables. You cannot update/delete any specific character. This will lead to error.
For example, Below operations are not permitted.
del str[2]
str[2] ='B'
# creating string in python
if __name__ == "__main__":
# How string are created.
string1 = "This is String 'in double inverted'"
string2 = 'This is Also a "string" '
string3 = """Multiline string should be used inside three times double/single inverted comma"""
print(f"String 1: {string1}")
print(f"String 2: {string2}")
print(f"String 3: {string3}")
Now, Let's discuss ways to remove a charecter from string.
In the example below, we create a new string, and loop through it. If we encounter the required character, we simply don’t include it in our new string. To find if the character is present, we can either do a direct check or if know the position of the character, we can do an index check.
Let us do an example.
if __name__ =="__main__":
str1 = "Python" # string created.
result = "" # this will hold our result.
# remove P from str1
for i in str1:
if(i!="P"):
result+= i
print(result) #output ython
# Index based.
# remove character at 3rd index.
print("____________")
result =""
for i in range(len(str1)):
if( i !=3 ):
result+=str1[i]
print(result )
Strings are immutable in python. So in step result += i, we are creating length(str1) -1 a new string. This will consume extra memory.
syntax: stringName.replace(old character, no of characters to remove)
3rd argument is an option, if not specified it will remove all characters
if __name__ =="__main__":
str1 = "Python Programming"
# remove one or all occurrences of n (character) using replace method.
print("String after replced: "+str1.replace('n','',2))
print("--")
print("Original String: "+str1) # .replace returns a new string, not updates the original string.
This method is useful if you know the index of the element that should be removed. In Python, we can access part of string using [ ].
[] operator
if __name__ == "__main__":
str1="String"
# str1[start index: end index(Not excluded): gap number]
print(str1[::-1]) # will print string in reverse order
print(str1[::2]) # if nothing given , it will skip every alternate character
print(str1[:3:-1]) # skip the first 4 characters and print the remaining characters in reverse order
if __name__=="__main__":
str1 = "Python"
print ("Original string: " + str1)
# remove at index 2
str1 = str1[:2]+str1[3:]
# as in range [a:b] b is excluded and index counting starts from left to right.
print ("String after removal of character: " + str1)
Syntax: Join method :
lis1 = ['P','Y','T','O','N']
s = "=="
s = s.join(lis1)
print(s,type(s))
output :
P==Y==T==O==N <class 'str'>
As we see above, join method is used to build a string from a list. In the above example, we built a string from the list of characters. To join these characters, we used '=='.
The result is returned as a new string.
str1 = "Python"
print("Original string: " + str1)
# Removing char at index 2
# using join() + list comprehension
result_str = ''.join([str1[i] for i in range(len(str1)) if i != 2])
# quite the same as the brute force method.
# As join is a pure concatenating method.
print ("String after removal of character: " + result_str)
Syntax : Translate method
string.translate(mapping)
mapping – a dictionary(key-value pair) having mapping between two characters...
translate() returns a a modified string using translation mappings or table.
Example:
if __name__ =="__main__":
str1 = 'ABCDEF_PYTHON_ABCD_PYTHON'
print(str1.translate({ord(i): None for i in 'PYTHON'}))
Related Notebooks
- Remove An Item From A List In Python Using Clear Pop Remove And Del
- How To Take String Input From Command Line In Python
- Return Multiple Values From a Function in Python
- Python Pandas String To Integer And Integer To String DataFrame
- String And Literal In Python 3
- 3 Ways to Rename Columns in Pandas DataFrame
- How to Plot a Histogram in Python
- How To Take Integer Input From Command Line In Python
- A Study of the TextRank Algorithm in Python