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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40113223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:10:33  来源:igfitidea点击:

Return last character of string in python

python

提问by Amar

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

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

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

我打电话给str[-1]但它没有按预期工作。

t.txt contains

t.txt 包含

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.

但它没有打印任何东西。

回答by alecxe

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

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

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

回答by Sameer

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]