返回Python中字符串的最后一个字符


问题内容

我想打印从文件读取的python中字符串的最后一个字符。

我正在打电话,str[-1]但没有按预期工作。

t.txt包含

Do not laugh please!        9

Are you kidding me?     4

我的代码是

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

但是它没有打印任何东西。


问题答案:

每行的最后一个字符是 换行符
。您可以剥离它:

print(line.strip()[-1])  
# or print(line.rstrip()[-1])