Python: How to remove [' and ']?

前端 未结 4 678
说谎
说谎 2021-01-29 11:36

I want to remove [\' from start and \'] characters from the end of a string.

This is my text:

\"[\'45453656565\']\"


        
相关标签:
4条回答
  • 2021-01-29 11:51

    You need to strip your text by passing the unwanted characters to str.strip() method:

    >>> s = "['45453656565']"
    >>> 
    >>> s.strip("[']")
    '45453656565'
    

    Or if you want to convert it to integer you can simply pass the striped result to int function:

    >>> try:
    ...     val = int(s.strip("[']"))
    ... except ValueError:
    ...     print("Invalid string")
    ... 
    >>> val
    45453656565
    
    0 讨论(0)
  • 2021-01-29 11:56

    Instead of hacking your data by stripping brackets, you should edit the script that created it to print out just the numbers. E.g., instead of lazily doing

    output.write(str(mylist))
    

    you can write

    for elt in mylist:
        output.write(elt + "\n")
    

    Then when you read your data back in, it'll contain the numbers (as strings) without any quotes, commas or brackets.

    0 讨论(0)
  • 2021-01-29 12:06

    Using re.sub:

    >>> my_str = "['45453656565']"
    >>> import re
    >>> re.sub("['\]\[]","",my_str)
    '45453656565'
    
    0 讨论(0)
  • 2021-01-29 12:08

    You could loop over the character filtering if the element is a digit:

    >>> number_array =  "['34325235235']"
    >>> int(''.join(c for c in number_array if c.isdigit()))
    34325235235
    

    This solution works even for both "['34325235235']" and '["34325235235"]' and whatever other combination of number and characters.

    You also can import a package and use a regular expresion to get it:

    >>> import re
    >>> theString = "['34325235235']"
    >>> int(re.sub(r'\D', '', theString)) # Optionally parse to int
    
    0 讨论(0)
提交回复
热议问题