Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does [-1] not return the last character of the line in a file?

Tags:

python

I want to print the last character of string in python reading from the file.

I am calling as str[-1] but it is not working as expected.

t.txt contains

Do not laugh please!        9
    
Are you kidding me?     4

My code is

with open('t.txt', 'r') as f:
    for line in f:
        print(line)
        print(line[-1])
        # break

But it is not printing anything.

like image 203
Amar Avatar asked Oct 18 '16 16:10

Amar


2 Answers

The last character of every line is a newline character. You can strip it:

print(line.strip()[-1])  
# or print(line.rstrip()[-1])
like image 153
alecxe Avatar answered Jan 16 '23 12:01

alecxe


Simple, take the string and clear it's leading and trailing spaces. Then return the last character in your case. Otherwise simply return last character.

line=line.strip()
return line[-1]
like image 30
Sameer Avatar answered Jan 16 '23 11:01

Sameer