How can I strip first and last double quotes?

后端 未结 13 1234
抹茶落季
抹茶落季 2020-12-02 10:14

I want to strip double quotes from:

string = \'\"\" \" \" \"\"\\\\1\" \" \"\" \"\"\'

to obtain:

string = \'\" \" \" \"\"\\\         


        
相关标签:
13条回答
  • 2020-12-02 10:49

    Starting in Python 3.9, you can use removeprefix and removesuffix:

    '"" " " ""\\1" " "" ""'.removeprefix('"').removesuffix('"')
    # '" " " ""\\1" " "" "'
    
    0 讨论(0)
  • 2020-12-02 10:50

    If you are sure there is a " at the beginning and at the end, which you want to remove, just do:

    string = string[1:len(string)-1]
    

    or

    string = string[1:-1]
    
    0 讨论(0)
  • 2020-12-02 10:50

    Below function will strip the empty spces and return the strings without quotes. If there are no quotes then it will return same string(stripped)

    def removeQuote(str):
    str = str.strip()
    if re.search("^[\'\"].*[\'\"]$",str):
        str = str[1:-1]
        print("Removed Quotes",str)
    else:
        print("Same String",str)
    return str
    
    0 讨论(0)
  • 2020-12-02 10:52

    Almost done. Quoting from http://docs.python.org/library/stdtypes.html?highlight=strip#str.strip

    The chars argument is a string specifying the set of characters to be removed.

    [...]

    The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:

    So the argument is not a regexp.

    >>> string = '"" " " ""\\1" " "" ""'
    >>> string.strip('"')
    ' " " ""\\1" " "" '
    >>> 
    

    Note, that this is not exactly what you requested, because it eats multiple quotes from both end of the string!

    0 讨论(0)
  • 2020-12-02 10:52

    I have some code that needs to strip single or double quotes, and I can't simply ast.literal_eval it.

    if len(arg) > 1 and arg[0] in ('"\'') and arg[-1] == arg[0]:
        arg = arg[1:-1]
    

    This is similar to ToolmakerSteve's answer, but it allows 0 length strings, and doesn't turn the single character " into an empty string.

    0 讨论(0)
  • 2020-12-02 10:56

    Remove a determinated string from start and end from a string.

    s = '""Hello World""'
    s.strip('""')
    
    > 'Hello World'
    
    0 讨论(0)
提交回复
热议问题