Python - 获取字符串的最后 N 个字符
给定一个字符串和一个整数 N,任务是编写一个Python程序来打印字符串的最后 N 个字符。
例子:
Input: Geeks For Geeks!; N = 4
Output: eks!
Explanation: The given string is Geeks For Geeks! and the last 4 characters is eks!.
Input: PYTHON; N=1
Output: N
Explanation: The given string is PYTHON and the last character is N.
方法 1:使用循环获取给定字符串的最后 N 个字符。
Python3
# get input
Str = "Geeks For Geeks!"
N = 4
# print the string
print(Str)
# iterate loop
while(N > 0):
# print character
print(Str[-N], end='')
# decrement the value of N
N = N-1
Python
# get input
Str = "Geeks For Geeks!"
N = 4
# print the string
print(Str)
# get length of string
length = len(Str)
# create a new string of last N characters
Str2 = Str[length - N:]
# print Last N characters
print(Str2)
输出:
Geeks For Geeks!
eks!
方法 2:使用列表切片打印给定字符串的最后 n 个字符。
Python
# get input
Str = "Geeks For Geeks!"
N = 4
# print the string
print(Str)
# get length of string
length = len(Str)
# create a new string of last N characters
Str2 = Str[length - N:]
# print Last N characters
print(Str2)
输出:
Geeks For Geeks!
eks!