0

I've got this example

a='Datenfernübertragung remote data transmission|long-distance data transmission|long-distance data transfer|remote data transmission   Preferred|Forbidden|Forbidden|'
b = a.split('\t')
for item in b[1].split('|'):
  indeks=b[1].split('|').index(item)
  print(indeks)

and it returns at this moment 0, 1, 2, 0 which are indexes of remote data transmission|long-distance data transmission|long-distance data transfer|remote data transmission but why it return to index 0, instead of printing index 3?

Thanks

3
  • 2
    Look into enumerate if you're trying to get the index Commented Jun 8, 2017 at 18:29
  • 1
    Because index finds the first instance of something. The first instance of remote data transmission in the split is the first element of the split. Commented Jun 8, 2017 at 18:50
  • Shaun can you post this as an answer, enumerate solve my problem. Thanks Commented Jun 8, 2017 at 18:51

1 Answer 1

2
Python 3.4.3 (default, Nov 17 2016, 01:11:57) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a='Datenfernübertragung remote data transmission|long-distance data transmission|long-distance data transfer|remote data transmission   Preferred|Forbidden|Forbidden|'
>>> b = a.split('\t')
>>> b
['Datenfernübertragung remote data transmission|long-distance data transmission|long-distance data transfer|remote data transmission   Preferred|Forbidden|Forbidden|']
>>> b[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

There is no any \t in your string, b is a single-item list and its index is zero. Thus your code snippet is completely wrong.

As I could understand you've took an attempt to derive indexes for vertical bar separated values in the string. Hope this snippet should do it in a much neat way:

>>> for i, j in enumerate(a.split('|')):
...     print(i, j)
... 
0 Datenfernübertragung remote data transmission
1 long-distance data transmission
2 long-distance data transfer
3 remote data transmission   Preferred
4 Forbidden
5 Forbidden
6 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.