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.
The last character of every line is a newline character. You can strip it:
print(line.strip()[-1])
# or print(line.rstrip()[-1])
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With