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


沒有留言:

張貼留言

[ Python 文章收集 ] SQLAlchemy quick start with PostgreSQL

Source From   Here   Preface   This is a quick tutorial for getting started with   SQLAlchemy Core API .   Prerequisites   In this quick st...