2018年7月12日 星期四

[ Python 常見問題 ] Splitting on first occurrence

Source From Here 
Question 
What would be the best way to split a string on the first occurrence of a delimiter? 
For example: 
>>> s = 'John: Hello, my link is http://abc.com' 
>>> s.split() // Split with space 
['John:', 'Hello,', 'my', 'link', 'is', 'http://abc.com'] 
>>> s.split(':') // Split with delimiter ':' 
['John', ' Hello, my link is http', '//abc.com']

How do I split with first ':' to get: ['John', 'Hello, my link is http://abc.com'] ? 

How-To 
From the docs: 
str.split([sep[, maxsplit]]) 
Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements).

So the sample code: 
>>> map(lambda e: e.strip(), s.split(':', 1)) 
['John', 'Hello, my link is http://abc.com']


沒有留言:

張貼留言

[ Py DS ] Ch1 - IPython: Beyond Normal Python

Source From  Here   Keyboard Shortcuts in the IPython Shell   If you spend any amount of time on the computer, you’ve probably found a u...