Python - 访问给定字符串中第 K 个索引处的元素
给定一个字符串,访问第 K 个索引处的元素。
Input : test_str = ‘geeksforgeeks’, K = 4
Output : s
Explanation : s is 4th element
Input : test_str = ‘geeksforgeeks’, K = 24
Output : string index out of range
Explanation : Exception as K > string length.
方法 #1:使用 []运算符
这是执行此任务的基本方式。在这里,我们只是将第 K 个索引括在方括号中。如果 K 可以大于字符串的长度,则建议将其包含在 try-except 块中。
Python3
# Python3 code to demonstrate working of
# Access element at Kth index in String
# Using []
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 7
# try-except block for error handling
try :
# access Kth element
res = test_str[K]
except Exception as e :
res = str(e)
# printing result
print("Kth index element : " + str(res))
Python3
# Python3 code to demonstrate working of
# Access element at Kth index in String
# Using Negative index + len() + [] operator
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 7
# try-except block for error handling
try :
# access Kth element
# using negative index
res = test_str[-(len(test_str) - K)]
except Exception as e :
res = str(e)
# printing result
print("Kth index element : " + str(res))
输出
The original string is : geeksforgeeks
Kth index element : r
方法 #2:使用负索引 + len() + []运算符
这是可以执行此任务的另一种方式。在这里,我们计算字符串的长度并从中减去 K,它从头开始得到第 K 个索引,并且索引为负。
蟒蛇3
# Python3 code to demonstrate working of
# Access element at Kth index in String
# Using Negative index + len() + [] operator
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 7
# try-except block for error handling
try :
# access Kth element
# using negative index
res = test_str[-(len(test_str) - K)]
except Exception as e :
res = str(e)
# printing result
print("Kth index element : " + str(res))
输出
The original string is : geeksforgeeks
Kth index element : r