Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string by backslash in python

Tags:

python

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" 

Tried to escape the the backslash but it doesn't seem to work:

 print(a.split('\'))  print(a.split('"\"'))  print(a.split('\\'))  print(a.split('"\\"')) 

I want to get this result:

 ['1','2','3','4'] 

Many thanks in advance

like image 686
user3184086 Avatar asked Jul 30 '14 22:07

user3184086


People also ask

How do you split a string in Python?

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

What does split ('\ t ') do in Python?

Python String split() Method. The split() method splits the string from the specified separator and returns a list object with string elements. The default separator is any whitespace character such as space, \t , \n , etc.

How do you use a forward slash in a string in Python?

Programming languages, such as Python, treat a backslash (\) as an escape character. For instance, \n represents a line feed, and \t represents a tab. When specifying a path, a forward slash (/) can be used in place of a backslash. Two backslashes can be used instead of one to avoid a syntax error.


1 Answers

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' 
like image 92
Henry Keiter Avatar answered Oct 02 '22 14:10

Henry Keiter