简体   繁体   English

如何用“-”为列表中的一项拆分字符串?

[英]How to split string by “-” for one item in a list?

I have a list with one item that I need to split by "-" to access the last segment of data: 我有一个包含一个项目的列表,需要用“-”分隔才能访问数据的最后一段:

a = ['1-35-047-13-6299\t1\n']

Normally, I would do this by using the following call: 通常,我将使用以下调用来做到这一点:

test = a.split("-")

However, this yields the following error 但是,这会产生以下错误

>>> a = ['1-35-047-13-6299\t1\n']
>>> a
['1-35-047-13-6299\t1\n']
>>> test = a.split("-")
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
AttributeError: 'list' object has no attribute 'split'
>>> 

How can I get at the last segment of data in the list item eg "6299\\t1\\n" using the split method? 如何使用split方法获取列表项中的最后一段数据,例如“ 6299 \\ t1 \\ n”?

test = a[0].split('-')[-1]
print test

You have at least two problems here. 您在这里至少有两个问题。 For one thing, as the error message says split expects a string rather than a list, but a is a list of strings rather than a string. 一方面,错误消息说split期望一个字符串而不是一个列表,但是a是一个字符串列表而不是一个字符串。 So split needs a[0] for this specific case, or in general something you can trust to be a string. 因此,在这种情况下, split需要a[0] ,或者一般来说,您可以相信它是字符串。

Then there's the need to split off just the rightmost element. 然后,需要仅分割最右边的元素。 That's what rsplit is for, probably with the parameter that limits the number of splits. 这就是rsplit目的,可能是使用限制拆分次数的参数。 So bottom line you want something like: 因此,您想要的底线是:

test = a[0].rsplit('-',1)[1]

Even that will fail if your input string does not contain a - character - either capturing the whole output of rsplit and checking its length or using reverse indexing into its output would work to guard against that case. 如果您的输入字符串不包含-字符,那么即使失败也将失败-捕获rsplit的整个输出并检查其长度,或者在其输出中使用反向索引都可以防止这种情况。

the traceback show that : 'list' object has no attribute 'split' 追溯显示: 'list' object has no attribute 'split'

'String' object has the attribute 'split', you can use a[i].split('-') “字符串”对象的属性为“拆分”,可以使用a[i].split('-')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM