开发者

Replace the single quote (') character from a string

开发者 https://www.devze.com 2023-01-05 02:06 出处:网络
I need to strip the开发者_如何学Go 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

I need to strip the开发者_如何学Go 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.


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)
    


Do you mean like this?

>>> mystring = "This isn't the right place to have \"'\" (single quotes)"
>>> mystring
'This isn\'t the right place to have "\'" (single quotes)'
>>> newstring = mystring.replace("'", "")
>>> newstring
'This isnt the right place to have "" (single quotes)'


You can escape the apostrophe with a \ character as well:

mystring.replace('\'', '')


I met that problem in codewars, so I created temporary solution

pred = "aren't"
pred = pred.replace("'", "99o")
pred = pred.title()
pred = pred.replace("99O", "'")
print(pred)

You can use another char combination, like 123456k and etc., but the last char should be letter

0

精彩评论

暂无评论...
验证码 换一张
取 消