linecache and comparison with input

R

Ross Hetherington

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512

Say I've got a file called 'testfile' that contains the following three
lines:

foo
bar
baz

And a script that goes like this:

#!/usr/bin/env python

import random
import sys
import linecache

rnd = random.randint(1,3)
line = linecache.getline('testfile', rnd)

print line

gss = raw_input('Enter line: ',)

if gss == line:
print 'yes'
sys.exit()
else:
print 'no'


Even if the right word is entered, the script always prints `no'. Can
anyone explain why this happens?
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.7 (GNU/Linux)
Comment: Using GnuPG with Fedora - http://enigmail.mozdev.org

iD8DBQFGhmUm0HlvQApfM3gRCl23AJ45cv7A0KVi2h8/cWmcCrg4X8HZOACfT6V8
IpXAzpD0jKnFFDEJEmOFvc4=
=UA5b
-----END PGP SIGNATURE-----
 
S

Sebastian Wiesner

[ Ross Hetherington said:
#!/usr/bin/env python

import random
import sys
import linecache

rnd = random.randint(1,3)
line = linecache.getline('testfile', rnd)

print line Try print repr(line) ...

gss = raw_input('Enter line: ',)
and print repr(gss) ;)
if gss == line:
print 'yes'
sys.exit()
else:
print 'no'

Then you will see, that getline returns the line *including the newline
character*, while raw_input does not. Use line.strip('\n') to remove
trailing newline characters from the return value of getline.

--
Freedom is always the freedom of dissenters.
(Rosa Luxemburg)

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.4 (GNU/Linux)

iD4DBQBGhmhrn3IEGILecb4RAs4LAKCkE7r5b5CAXi3Et2eYQ0FJlWDTdgCYtMGd
DBzXXDbb2jIOpuJD3XRokA==
=Mmo7
-----END PGP SIGNATURE-----
 
R

Ross Hetherington

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512

Sebastian said:
Then you will see, that getline returns the line *including the newline
character*, while raw_input does not. Use line.strip('\n') to remove
trailing newline characters from the return value of getline.

Ah, thank you. I did notice that getline left a trailing newline, but I
didn't realise raw_input didn't. Ooops.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.7 (GNU/Linux)
Comment: Using GnuPG with Fedora - http://enigmail.mozdev.org

iD8DBQFGhml20HlvQApfM3gRCozzAJ0QAENDkQn8StlEr9Mh0yoCCkUhzQCcCmOC
5tPusqS4MwnisNLZmtKc3Y4=
=hlHr
-----END PGP SIGNATURE-----
 

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,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top