简体   繁体   English

如何将字符串拆分为python中不包含空格的单词?

[英]How to split string into words that do not contain whitespaces in python?

My string is: 我的字符串是:

"This     is a      string"

I want to turn it into a list: 我想把它变成一个列表:

["This", "is", "a", "string"]

I use the split(" ") method, but it adds whitespaces as list elements. 我使用split(" ")方法,但它添加了空格作为列表元素。 Please help, 请帮忙,

Best Regards 最好的祝福

>>> v="This is a  string"

>>> v.split()
['This', 'is', 'a', 'string']

just use split() . 只需使用split()

It won't add whitespace as elements if you just use .split() , instead of .split(' ') 如果你只使用.split()而不是.split(' ') ,它不会将空格添加为元素

>>> "This     is a     string".split()
['This', 'is', 'a', 'string']

Like the docs say, don't pass an argument. 就像文档说的那样,不要传递论据。

>>> "This is a string".split()
['This', 'is', 'a', 'string']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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