为什么 split() 结果中返回空字符串? [英] Why are empty strings returned in split() results?

查看:61
本文介绍了为什么 split() 结果中返回空字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

'/segment/segment/'.split('/') 返回 ['', 'segment', 'segment', ''] 的意义是什么?

注意空元素.如果您在一个恰好位于字符串末尾的分隔符上进行拆分,那么从每一端返回空字符串会给您带来什么额外的值?

Notice the empty elements. If you're splitting on a delimiter that happens to be at position one and at the very end of a string, what extra value does it give you to have the empty string returned from each end?

推荐答案

str.split 补充 str.join,所以

"/".join(['', 'segment', 'segment', ''])

让您返回原始字符串.

如果不存在空字符串,则 join() 之后的第一个和最后一个 '/' 将丢失.

If the empty strings were not there, the first and last '/' would be missing after the join().

这篇关于为什么 split() 结果中返回空字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆