Return last character of string in python

前端 未结 2 760
走了就别回头了
走了就别回头了 2021-01-05 08:59

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.

相关标签:
2条回答
  • 2021-01-05 09:23

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

    print(line.strip()[-1])  
    # or print(line.rstrip()[-1])
    
    0 讨论(0)
  • 2021-01-05 09:44

    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]
    
    0 讨论(0)
提交回复
热议问题