I need to strip the character "'"
from a string in python. How do I do this?
I know there is a simple answer. Really what I am looking for is how to write '
in my code. for example \n
= newline.
Use the String. replace() method to replace single with double quotes, e.g. const replaced = str. replace(/'/g, " ); . The replace method will return a new string where all occurrences of single quotes are replaced with double quotes.
Method 1 : Using the replace() method To replace a single quote from the string you will pass the two parameters. The first is the string you want to replace and the other is the string you want to place. In our case it is string. replace(” ' “,” “).
This uses String. replace(CharSequence, CharSequence) method to do string replacement. Remember that \ is an escape character for Java string literals; that is, "\\'" contains 2 characters, a backslash and a single quote.
To erase Quotes (“”) from a Python string, simply use the replace() command or you can eliminate it if the quotes seem at string ends.
As for how to represent a single apostrophe as a string in Python, you can simply surround it with double quotes ("'"
) or you can escape it inside single quotes ('\''
).
To remove apostrophes from a string, a simple approach is to just replace the apostrophe character with an empty string:
>>> "didn't".replace("'", "") 'didnt'
Here are a few ways of removing a single '
from a string in python.
str.replace
replace
is usually used to return a string with all the instances of the substring replaced.
"A single ' char".replace("'","")
str.translate
In Python 2
To remove characters you can pass the first argument to the funstion with all the substrings to be removed as second.
"A single ' char".translate(None,"'")
In Python 3
You will have to use str.maketrans
"A single ' char".translate(str.maketrans({"'":None}))
re.sub
Regular Expressions using re
are even more powerful (but slow) and can be used to replace characters that match a particular regex rather than a substring.
re.sub("'","","A single ' char")
Other Ways
There are a few other ways that can be used but are not at all recommended. (Just to learn new ways). Here we have the given string as a variable string
.
Using list comprehension
''.join([c for c in string if c != "'"])
Using generator Expression
''.join(c for c in string if c != "'")
Another final method can be used also (Again not recommended - works only if there is only one occurrence )
Using list
call along with remove
and join
.
x = list(string) x.remove("'") ''.join(x)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With