0
import fileinput

for line in fileinput.input("emaillist.txt"):
        line=line.rstrip('\n\r ')
        line= line.split('=')
        newlin = line[1]

why is this not valid? I am trying to break up the nasty looking line of text and make something useful out of it? Doesnt the split() function produce a list, which you can address via list[x] ?

Thanks!!!!

Traceback (most recent call last):
  File "./clean.py", line 8, in <module>
    newlin = line[1]
IndexError: list index out of range
Cmag
  • 14,946
  • 25
  • 89
  • 140

3 Answers3

4

You could use line.partition('=')[2] if '=' is sometimes missing:

>>> 'a = b'.partition('=')
('a ', '=', ' b')
>>> 'a'.partition('=')
('a', '', '')

Compare it to split():

>>> 'a = b'.split('=')
['a ', ' b']
>>> 'a'.split('=')
['a']
jfs
  • 399,953
  • 195
  • 994
  • 1,670
  • 2
    Bingo. That was one of the motivations for introducing str.partition() to Python. Since you always know that it produces a three-tuple, it is easier to work with than str.split() for applications such as this. – Raymond Hettinger Oct 26 '11 at 02:08
1

Doesnt the split() function produce a list, which you can address via list[x] ?

Yes. But if the list only has one element then you can't index it with anything non-negative other than 0.

>>> 'foo'.split('=')
['foo']
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

Try checking to see how many parts the line was split into first:

import fileinput

for line in fileinput.input("emaillist.txt"):
    line = line.rstrip('\n\r ').split('=')
    if len(line) > 1:
        newline = line[1]
        # ...
    else:
        # do something else...

Or, in 1 line ([line.rstrip('\n\r ').split('=')[1] for line in fileinput.input("emaillist.txt") if len(line.rstrip('\n\r ').split('=')) > 1]):

emaillist.txt:

Email1=123@bob.com
email2=abc@123.com

emails = [line.rstrip('\n\r ').split('=')[1] for line in fileinput.input("emaillist.txt") if len(line.rstrip('\n\r ').split('=')) > 1]
print emails
['123@bob.com', 'abc@123.com']
chown
  • 51,908
  • 16
  • 134
  • 170