Reputation: 25
I want to print True if the word/line is a palindrome. The code reads the text from the text file (using sys.argv[1]). I don't understand why it's only checks the first line.
text file:
racecar
AddE
HmllpH
Was it a car or a cat I saw
Hannah
T can arise in context where language is played wit
Able was I ere I saw Elba
Doc note I dissent A fast never prevents a fatness I diet on cod
code:
import sys
filename = sys.argv[1]
with open(filename, "r") as f:
text = f.readline().strip().lower()
while text:
palindrome = True
i = 0
while i < len(text) / 2:
if text[i] != text[len(text) - 1 - i]:
palindrome = False
i += 1
if palindrome:
print(True)
text = f.readline().strip()
output:
True
Upvotes: 1
Views: 57
Reputation: 6298
Only the first line is a case-sensitive palindrome.
Some explanation on what you see:
2.1. The loop for text in map(str.strip, f)
, means that we are going over file f
lines and apply the str.strip()
method on each of them.
2.2. text.upper()
to convert text to unified upper case, for common comparison.
2.3. text_upper[::-1]
to reverse text: The strange [::-1]
index notation, means that we are going on all elements backward one step (therefore the -1).
import sys
filename = 'outfile.txt'
with open(filename, "r") as f:
for text in map(str.strip, f):
text_upper = text.upper()
if text_upper == text_upper[::-1]:
print(f'{text} is palindrom!')
Upvotes: 3
Reputation: 95
It does check all lines, but only the first case returns True because the other lines don't have .lower()
. You would have to change the last line to text = f.readline().strip().lower()
.
Upvotes: 0