所以我有一个由空格和制表符分隔的大字符串,想知道快速将每个单词附加到列表中的方法。
例如:
x = "hello Why You it from the"
list1 = ['hello', 'why', 'you', 'it','from', 'the']
这个字符串中有制表符和多个单词之间变化的空格,我需要一个快速的解决方案,而不是手动修复问题。
str.split
:>>> x = "hello Why You it from the"
>>> x.split()
['hello', 'Why', 'You', 'it', 'from', 'the']
>>> x = "hello Why You it from the"
>>> x.split()
['hello', 'Why', 'You', 'it', 'from', 'the']
>>>
str.split
之前调用 str.lower
。>>> x = "hello Why You it from the"
>>> x.lower().split()
['hello', 'why', 'you', 'it', 'from', 'the']
>>>
str.split()
可以完成这个任务:
>>> x = "hello Why You it from the"
>>> x.split()
['hello', 'Why', 'You', 'it', 'from', 'the']
>>> x.lower().split()
['hello', 'why', 'you', 'it', 'from', 'the']
从上面的链接中:
如果未指定
sep
或为None
,则将应用不同的拆分算法:连续的空白字符被视为单个分隔符,并且如果字符串具有前导或尾随空格,则结果将不包含开头或结尾的空字符串。
sep
是 split()
的第一个参数。
x.lower().split()
怎么样? - arshajii