首页 > 解决方案 > Splitting a String based on tabs and spaces

问题描述

How can i split a String with delimeters being \t and ' '(space)? For example:

string="\t Hello   World\t"
newString=['Hello','World']

标签: pythonpython-3.x

解决方案


Use re.split with the delimiter [\t ]+:

string = "\t Hello   World\t"
parts = re.split(r'[\t ]+', string.strip())
print(parts)

This prints:

['Hello', 'World']

Note that I strip the leading and trailing whitespace before calling re.split. Also, if you would accept just splitting on any whitespace, we could have used re.split(r'\s+', string.strip()) instead.


推荐阅读