Reputation: 181
I have a string which contains the following information.
mystring = "'$1$Not Running', ''"
I want to be able to remove the extra space and , ''
after the Running. I tried to use strip()
but it does not seem to work.
My desired output is mystring = "'$2$Not Running'"
I am not sure what I am missing here? Any help is appreciated.
Upvotes: 1
Views: 254
Reputation: 23528
If the 4 characters you want to replace are ', '
then you can just use the string.replace()
function to replace them with an empty string ''
:
mystring = mystring.replace( "', '", '')
Upvotes: 0
Reputation: 92
Maybe there is something better but you can try to use split()
mynewstring = mystring.split()[0] + mystring.split()[1]
Upvotes: 0
Reputation: 1025
strip()
only removes spaces as the beginning and end of a string. Since what you want to remove is in the middle, it won't work for you.
You can use regular expressions to search and replace for specific strings:
import re
mystring = "'$1$Not Running', ''"
mynewstring = re.sub(", ''", "", mystring)
print(mynewstring)
# '$1$Not Running'
I'm not sure what extra space you're talking about, but you can use similar logic to replace it.
If this is literally the only thing you need it for, then some of the other answers might be simpler. If you need it for several different cases of input, this might be a better option. We'd need to see more examples of input to figure that out though.
Upvotes: 1
Reputation: 263
i assume you want to remove the final 4 char's in your string. To do this you can simply
mystring = mystring[:-4]
if this is not right tell me and ill try to find a solution
Upvotes: 1
Reputation: 27283
One of the easier solutions would be to partition
your string based on the comma:
mystring, comma, rest = mystring.partition(",")
This solution depends on there not being any commas in the string other than that one.
The better solution would be to figure out why the extra characters are in your string and what you can do to avoid it.
If that isn't possible, it looks like the string is valid Python, so you could parse it as a tuple and always pick the first element:
import ast
mystring, _ = ast.literal_eval(mystring)
Although in this case you would get what's inside the single quotes, not the single quotes as characters themselves.
Upvotes: 3