I require a program that will remove all trailing whitespace (any spaces that occur at the end of a line) from a text file. It should do something like:

Space Stripper
Enter the name of the file to be stripped: news.txt

Any help would be gladly appreciated.

I'm also seeking help for writing a recursive function search(l,key) that returns a boolean: True if key is in the list l; False if it isn't. The in operator and the index() list method both can't be used. It should report the position of the key, if present. Something like search(l,key) returning the index of key in l, or False, if key is not present.

def search(l,key):

#- sample main -#
l1 = [1, '2', 'x', 5, -2]
print search(l1, 'x')  # should output: "2"
print search(l1, 2)    # should output: "False"

Try string.strip():

import string
text_file=string.strip(text_file)

As for opening the file... I Am not sure (I am a newb :( )...

You need to read your text file line by line. If the line has trailing spaces, it will most likely still end with a newline character. You can use
line = line.rstrip()
to strip all trailing white spaces including the newline character. Now if you want to write the stripped line back out to a file, you wll have to concatenate the newline character '\n' to the end of each line.

Just a helpful hint, don't use ll as a variable name it looks too much like l1 or 11. An easy way to introduce bugs into your code.

As to your second problem, hopefully you can iterate over the list with a for loop, since that has in in it.

My answer to your first question:

stripped = []

print "Input the file, including it's full path, to strip"
a = raw_input("--> ")

stripper =  open(a, 'r')
st_lines = stripper.readlines()
stripper.close()

for lines in st_lines:
    stripped_line = " ".join(lines.split())
    stripped.append(stripped_line)

print "\n".join(stripped)

I don't know how to answer the second question, because you throw out the use of 'in' and 'index()' which makes the answer tricky.

If I could use them, I would:

li = [1, 2, '3', 'x', 'bob']

# Test
def isItInList(val):
    return val in li and li.index(val) or False

test_vals = [1, '2', 25, 'a', 'bob', 'duck']
for a in test_vals:
    print isItInList(a)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.