Skip to content Skip to sidebar Skip to footer

How Can I Separate This Into Two Strings?

I am new to Python, I am not sure what should I be looking for but I assure you I have done my research and still came up with a rather ugly 20 lines long block of code for this si

Solution 1:

split('/') should definitely be used and that should help you parse the URL.

If that is not sufficient, urlparse should be used to parse

urlparse.urlparse(path)
In [31]: url = 'http://stackoverflow.com/questions/12809298/how-can-i-separate-this-into-two-strings/12809315#12809315'

In [32]: urlparse.urlparse(url)
Out[32]: ParseResult(scheme='http', netloc='stackoverflow.com', path='/questions/12809298/how-can-i-separate-this-into-two-strings/12809315', params='', query='', fragment='12809315')

In [33]: a = urlparse.urlparse(url)

In [34]: a.path
Out[34]: '/questions/12809298/how-can-i-separate-this-into-two-strings/12809315'

In [35]: a.path.split('/')
Out[35]: 
['',
 'questions',
 '12809298',
 'how-can-i-separate-this-into-two-strings',
 '12809315']

Solution 2:

The first thing I would try is the .split() string function:

>>> url = "/block_1/block_2">>> url.split("/")
['', 'block_1', 'block_2']

This will return a list of components of the string, that were separated by the / character. From there, you can use the len() function to find out the length of the list, and take the appropriate action according to your desired logic.

Post a Comment for "How Can I Separate This Into Two Strings?"