str.split() 在返回的 List 中包含空格作为元素

问题描述 投票:0回答:1

我正在尝试使用 split() 函数将路径名称拆分为由“/”分隔的标记。

示例:路径 = "/a/b///c/../d/.//f"

列表=路径.split('/')

我期望输出列表为 list = ['a', 'b', 'c', '..', 'd', '.', 'f') 但实际输出是 ['', ' a'、'b'、''、''、'c'、'..'、'd'、'.'、''、'f']。为什么返回的列表中有空元素?谢谢您的帮助。

python string split
1个回答
0
投票
The split() function in Python splits a string at each occurrence of the specified separator and returns a list of the substrings. When you use split('/') on your path string "/a/b///c/../d/.//f", it splits the string at every /.

Here's a breakdown of how the splitting happens:

The first character is /, so splitting here results in an empty string before it (hence the first empty string in your list).
Then, it finds a, b, c, .., d, . and f as separate tokens.
However, wherever there are consecutive / characters (like ///), splitting at each of them results in empty strings for those positions where there's nothing between two / characters.
This is why you see empty strings in your resulting list. Each of them represents a position where there was a / followed immediately by another / without any characters in between.

To get the output you expected, you can use a list comprehension to filter out the empty strings: path = "/a/b///c/../d/.//f"
lst = [token for token in path.split('/') if token]
© www.soinside.com 2019 - 2024. All rights reserved.