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']


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...