Split a string by backslash in python

后端 未结 5 1197
悲哀的现实
悲哀的现实 2020-12-06 09:41

Simple question but I\'m struggling with it for too much time. Basically I want to split a string by \\ (backslash).

 a = \"1\\2\\3\\4\"

Tr

5条回答
  •  抹茶落季
    2020-12-06 10:01

    You have the right idea with escaping the backslashes, but despite how it looks, your input string doesn't actually have any backslashes in it. You need to escape them in the input, too!

    >>> a = "1\\2\\3\\4"  # Note the doubled backslashes here!
    >>> print(a.split('\\'))  # Split on '\\'
    ['1', '2', '3', '4']
    

    You could also use a raw string literal for the input, if it's likely to have many backslashes. This notation is much cleaner to look at (IMO), but it does have some limitations: read the docs!

    >>> a = r"1\2\3\4"
    >>> print(a.split('\\'))
    ['1', '2', '3', '4']
    

    If you're getting a elsewhere, and a.split('\\') doesn't appropriately split on the visible backslashes, that means you've got something else in there instead of real backslashes. Try print(repr(a)) to see what the "literal" string actually looks like.

    >>> a = '1\2\3\4'
    >>> print(a)
    1☻♥♦
    >>> print(repr(a))
    '1\x02\x03\x04'
    
    >>> b = '1\\2\\3\\4'
    >>> print(b)
    1\2\3\4
    >>> print(repr(b))
    '1\\2\\3\\4'
    

提交回复
热议问题