本文介绍了拆分多个空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序需要拆分以下格式的行:

I have a program that needs to split lines that are of the format:

IDNumber      Firstname Lastname    GPA      Credits

但我想将 FirstnameLastname 保留在同一个字符串中.

but I want to keep Firstname and Lastname in the same string.

有没有什么简单的方法可以做到这一点(除了拆分成五个字符串而不是四个)并且以某种方式让 split 方法只在有多个空格时拆分?

Is there any easy way to do this (other than just splitting into five strings instead of four) and somehow have the split method only split when there is more than one space?

推荐答案

如果你想用任何空格分割,你可以使用str.split:

If you want to split by any whitespace, you can use str.split:

mystr.split()

# ['IDNumber', 'Firstname', 'Lastname', 'GPA', 'Credits']

对于两个或更多空格:

list(filter(None, mystr.split('  ')))

# ['IDNumber', 'Firstname Lastname', 'GPA', 'Credits']

这篇关于拆分多个空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 14:11