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
2
  • guys, lol, im not a spammer btw, exporting things form mailman and importing into phplist Commented Oct 26, 2011 at 1:41
  • 2
    does every line have an equals sign in it? Commented Oct 26, 2011 at 1:42

3 Answers 3

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']
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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']

Comments

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:

[email protected]
[email protected]

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.