How to Delete a Character from a String in Python
Created
Modified
Using replace Method
The str.replace(old, new[, count])
method returns a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
See the following example:
#!/usr/bin/python3
s = "Hello"
s = s.replace("l", "")
print(s)
Heo
Using Slice Syntax
Specify the start index and the end index, separated by a colon, to return a part of the string.
For example,
#!/usr/bin/python3
# remove character
def remove(str, rep):
i = str.find(rep)
if i == -1:
return str
str = str[:i]+str[i+1:]
return remove(str, rep)
s = "Hello"
s = remove(s, 'l')
print(s)
Heo