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 常見問題 ] How to shift a datetime object by 12 hours in python

Source From   Here   Question   Datetime   objects hurt my head for some reason. I am writing to figure out   how to shift a date time obje...