Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python split string without splitting escaped character

Tags:

python-2.7

Is there a way to split a string without splitting escaped character? For example, I have a string and want to split by ':' and not by '\:'

http\://www.example.url:ftp\://www.example.url 

The result should be the following:

['http\://www.example.url' , 'ftp\://www.example.url'] 
like image 432
Daniel Yuen Avatar asked Aug 06 '13 23:08

Daniel Yuen


People also ask

How do you split a string with escape characters?

The standard solution is to use the split() method provided by the String class. It takes a regular expression as a delimiter and returns a string array. We can make the above code work by escaping the dot character. An escape character invokes an alternative interpretation on the following characters of a string.

How do you split a string at a specific position in Python?

Python String | split() separator : This is a delimiter. The string splits at this specified separator. If is not provided then any white space is a separator. maxsplit : It is a number, which tells us to split the string into maximum of provided number of times.

How do you split a string into parts based on a delimiter?

You can use the split() method of String class from JDK to split a String based on a delimiter e.g. splitting a comma-separated String on a comma, breaking a pipe-delimited String on a pipe, or splitting a pipe-delimited String on a pipe.


1 Answers

There is a much easier way using a regex with a negative lookbehind assertion:

re.split(r'(?<!\\):', str) 
like image 68
user629923 Avatar answered Oct 31 '22 04:10

user629923