返回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
Return last character of string in 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
回答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]