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

发布于 2025-01-04 01:58:52 字数 215 浏览 1 评论 0原文

我的字符串是:

"This     is a      string"

我想把它变成一个列表:

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

我使用 split(" ") 方法,但它添加空格作为列表元素。请帮忙,

最好的问候

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. Please help,

Best Regards

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

千紇 2025-01-11 01:58:52
>>> v="This is a  string"

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

只需使用 split() 即可。

>>> v="This is a  string"

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

just use split().

<逆流佳人身旁 2025-01-11 01:58:52

如果您只使用 .split() 而不是 .split(' '),它不会将空格添加为元素

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

It won't add whitespace as elements if you just use .split(), instead of .split(' ')

>>> "This     is a     string".split()
['This', 'is', 'a', 'string']
溇涏 2025-01-11 01:58:52

就像文档所说,不要传递参数。

>>> "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']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文