![](/img/trans.png)
[英]string as input to return only last character in Python, equivalent to lambda function
[英]Return last character of string in 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])
簡單地取字符串並清除它的前導和尾隨空格。 然后返回你案例中的最后一個字符。 否則只返回最后一個字符。
line=line.strip()
return line[-1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.