gpt4 book ai didi

python - Python 中的 Split vs Strip 以删除多余的空格

转载 作者:行者123 更新时间:2023-12-05 09:28:49 24 4
gpt4 key购买 nike

请问我是否需要在 split() 之前使用 strip() 来删除 Python 中的任何冗余空间(并在之后变成列表)?例如:

string1 = '   a      b '

我想要结果:

#list1=[a,b]

当我测试时,我发现 list1=string1.split() 就足够了。但不知何故,我的老师说 string1.strip().split() 是必需的。也许他错了?

最佳答案

根据documentation :

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

这意味着,strip() 的逻辑已经包含在split() 中,所以我认为,您的老师是错误的。 (请注意,如果您使用的是非默认分隔符,这将会改变。)

关于python - Python 中的 Split vs Strip 以删除多余的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71093424/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com