通过拆分字符串创建的 python 列表中的最后一个元素为空

Last element in python list, created by splitting a string is empty

所以我有一个字符串需要解析。该字符串包含多个单词,用连字符 (-) 分隔。该字符串还以连字符结尾。

例如one-two-three-.

现在,如果我想单独查看单词,我将字符串拆分为一个列表。

wordstring = "one-two-three-"
wordlist = wordstring.split('-')

for i in range(0, len(wordlist)):
     print(wordlist[i])

输出

one
two
three
#empty element

我不明白的是,为什么在结果列表中,最后一个元素是一个空字符串。 我怎样才能省略这个空元素?

我应该简单地截断列表还是有更好的方法来拆分字符串?

Strip/trim 拆分前的字符串。这样你将删除尾随的“\n”,你应该没问题。

您有一个空字符串,因为最后一个 - 字符的拆分在 RHS 上产生了一个空字符串。您可以在拆分之前从字符串中删除所有 '-' 个字符:

wordlist = wordstring.strip('-').split('-')

如果最后一个元素总是 一个 - 字符,您可以使用 [:-1] 省略它,它会获取字符串中除最后一个字符。

然后,像您一样继续split它:

wordlist = wordstring[:-1].split('-')
print(wordlist)
['one', 'two', 'three']

在拆分字符串之前,您应该使用 Python 的 strip built-in 函数。例如:

wordstring = "one-two-three-"
wordlist = wordstring.strip('-').split('-')

我相信 .split() 假设在最后一个 - 之后还有另一个元素,但它显然是一个空白条目。

您是否愿意在拆分之前删除 wordstring 中的破折号?

wordstring = "one-two-three-"
wordlist = wordstring[:-1].split('-')
print wordlist

OUT: 'one-two-three'

您可以使用正则表达式来执行此操作:

import re
wordlist = re.findall("[a-zA-Z]+(?=-)", wordstring)

输出:

['one', 'two', 'three']

这在the docs中有解释:

... If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']). ...

如果您知道您的字符串总是以 '-' 结尾,那么只需执行 wordlist.pop() 删除最后一个。

如果您需要更复杂的东西,您可能想了解 regular expressions

只是为了选择的多样性:

wordlist = [x for x in wordstring.split('-') if x]

请注意,上面还处理了以下情况:wordstring = "one-two--three-"(双连字符)

先 strip() 然后 split()

wordstring = "one-two-three-"
x = wordstring.strip('-')
y  = x.split('-')

for word in y:
    print word