catching empty strings (I guess that's what they are)

B

brad

I've began accepting user input :( in an old program. The input comes
from a simple text file where users enter filenames (one per line). What
is the appropriate way to handle blank lines that hold whitespace, but
not characters? Currently, I'm doing this:

for user_file in user_files:
# Remove whitespace and make lowercase.
file_skip_list.append(user_file.strip().lower())

file_skip_list = list(sets.Set(file_skip_list))

However, if the input file has blank lines in it, I get this in my list:

'' (that's two single quotes with noting in between)

I thought I could do something like this:

if user_file == None:
pass

Or this:

if user_file == '':
pass

But, these don't work, the '' is still there. Any suggestions are
appreciated!

Brad
 
D

Diez B. Roggisch

brad said:
I've began accepting user input :( in an old program. The input comes
from a simple text file where users enter filenames (one per line). What
is the appropriate way to handle blank lines that hold whitespace, but
not characters? Currently, I'm doing this:

for user_file in user_files:
# Remove whitespace and make lowercase.
file_skip_list.append(user_file.strip().lower())

file_skip_list = list(sets.Set(file_skip_list))

However, if the input file has blank lines in it, I get this in my list:

'' (that's two single quotes with noting in between)

I thought I could do something like this:

if user_file == None:
pass

Or this:

if user_file == '':
pass

But, these don't work, the '' is still there. Any suggestions are
appreciated!

They are still there because you perform the stripping and lowercasing in
the append-call. Not beforehand. So change the code to this:

for uf in user_files:
uf = uf.strip().lower()
if uf:
file_skip_list.append(uf)

Diez
 
B

brad

Diez said:
They are still there because you perform the stripping and lowercasing in
the append-call. Not beforehand.

Thank you. I made the changes. It works.
 
A

Alex Martelli

Diez B. Roggisch said:
for uf in user_files:
uf = uf.strip().lower()
if uf:
file_skip_list.append(uf)

This is fine; however, another reasonable alternative is:
if not uf.isspace():
file_skip_list.append(uf.strip().lower())

I prefer yours (it's simpler IMHO), but if I was doing a code review I
would accept either of these.


Alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top