简体   繁体   中英

Split string just after space

In Python 3.x, how would I split a string like this:

foo bar hello world

So the output would be a list like:

['foo ', 'bar ', 'hello ', 'world ']

If you want to handle and preserve arbitrary runs of whitespace, you'll need a regular expression:

>>> import re
>>> re.findall(r'(?:^|\S+)\s*', '   foo \tbar    hello world')
['   ', 'foo \t', 'bar    ', 'hello ', 'world']

Just split at whitespaces and then add them back again.

a = 'foo bar hello world'

splitted = a.split()  # split at ' '

splitted = [x + ' ' for x in splitted]  # add the ' ' at the end

Or if you want it a bit more fancy:

splitted = ['{} '.format(item) for item in a.split()]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM