How to remove underscores and spaces from a string effectively using Phython?
I am trying to strip the characters '_ ' (underscore and space) away from my string. The first code fails to strip anything. The code for word_1 works just as I intend. Could anyone enlighten me how to modify the first code to get output 'ale'?
word = 'a_ _ le'
word.strip('_ ')
word_1 = '_ _ le'
word_1.strip('_ ')
The possible reason for your first code might be falling to stripchar the characters '_' and ' ' from the string due to the operations. There may be a reason for assigning the modified string back to a variable. If you are facing this specific problem it looks like this:
String = “ _a_ le_”
Strong. Strip (' _ ')
Print (string) # output: “ _ a _le”
The “strip()” method will remove the character from the beginning and end of the string. But one thing you should remember is that it will not modify the original string in place. Therefore, to modify the original string in place you can use this:
String = “ _ a_ le _”
String = string. Script (' _ ')
Print (string). # output: “a _ le”
Therefore, this code will help you remove underscores from both the beginning and the end. But here is also a thing to remember it won't remove underscores within the string. If you are searching for ideas that can remove all underscores within the string, then you can follow or use the “replace()” strong method. Here is an example of it
# Original string
Strong = “ _a_ le_”
# Removing both underscores and space characters
New_string = string. replace( '_', ' '). replace( ' ', ' ')
Print (new_ string). # output: “ale”