Python - Access element at Kth index in given String
Last Updated :
05 Apr, 2023
Given a String, access element at Kth index.
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.
Method #1 : Using [] operator
This is basic way in which this task is performed. In this, we just enclose Kth index in square brackets. If K can be greater then length of string, its recommended to enclose in try-except block.
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))
OutputThe original string is : geeksforgeeks
Kth index element : r
Method #2 : Using Negative index + len() + [] operator
This is yet another way in which this task can be performed. In this, we compute length of string and subtract K from it, it results in Kth index from beginning, and negative indexed.
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))
OutputThe original string is : geeksforgeeks
Kth index element : r
The Time and Space Complexity for all the methods are the same
Time Complexity: O(1) -> Accessing an element in a list takes O(1), hence average time complexity of code is O(1)
Space Complexity: O(1)
Method #3: Using string slicing
- Initialize the string variable test_str with a string of your choice.
- Initialize the integer variable K with the index of the element you want to access.
- Use string slicing to get the element at the Kth index in the string. The syntax for string slicing is string[start:stop:step], where start is the starting index of the slice (inclusive), stop is the ending index of the slice (exclusive), and step is the step size between the elements in the slice. Since we only want to access a single element, we can set start and stop to K and K+1, respectively, and step to 1. Assign the result to the variable res.
- Print the value of res.
Python3
# Python3 code to demonstrate working of
# Access element at Kth index in String
# Using string slicing
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 7
# using string slicing to get the Kth element
res = test_str[K:K+1]
# printing result
print("Kth index element : " + str(res))
OutputThe original string is : geeksforgeeks
Kth index element : r
Time complexity: O(1) - accessing a single element in a string takes constant time.
Auxiliary space: O(1) - we only need a constant amount of space to store the string and integer variables.
Method #4: Using ord() function
Step-by-step approach:
- Initialize the string test_str and Kth index K value.
- Convert the character at the Kth index into its ASCII value using the ord() function.
- Return the character representation of the ASCII value obtained in step 2 using the chr() function.
- Print the character obtained in step 3 as the Kth index element of the string.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Access element at Kth index in String
# Using ord() function
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 7
# using ord() and chr() function to get the Kth element
res = chr(ord(test_str[K]))
# printing result
print("Kth index element : " + str(res))
OutputThe original string is : geeksforgeeks
Kth index element : r
Time Complexity: O(1)
Auxiliary Space: O(1)
Similar Reads
Find Index of Element in Array - Python In Python, arrays are used to store multiple values in a single variable, similar to lists but they offer a more compact and efficient way to store data when we need to handle homogeneous data types . While lists are flexible, arrays are ideal when we want better memory efficiency or need to perform
2 min read
Replace a String character at given index in Python In Python, strings are immutable, meaning they cannot be directly modified. We need to create a new string using various methods to replace a character at a specific index. Using slicingSlicing is one of the most efficient ways to replace a character at a specific index.Pythons = "hello" idx = 1 rep
2 min read
Python - Get Nth word in given String Sometimes, while working with data, we can have a problem in which we need to get the Nth word of a String. This kind of problem has many application in school and day-day programming. Let's discuss certain ways in which this problem can be solved. Method #1 : Using loop This is one way in which thi
4 min read
Python - Get Nth column elements in Tuple Strings Yet another peculiar problem that might not be common, but can occur in python programming while playing with tuples. Since tuples are immutable, they are difficult to manipulate and hence knowledge of possible variation solutions always helps. This article solves the problem of extracting only the
8 min read
Python - Insert character in each duplicate string after every K elements Given a string and a character, insert a character after every K occurrence. Input : test_str = 'GeeksforGeeks', K = 2, add_chr = ";" Output : [';GeeksforGeeks', 'Ge;eksforGeeks', 'Geek;sforGeeks', 'Geeksf;orGeeks', 'Geeksfor;Geeks', 'GeeksforGe;eks', 'GeeksforGeek;s'] Explanation : All combinations
3 min read
Python - Find Index containing String in List In this article, we will explore how to find the index of a string in a list in Python. It involves identifying the position where a specific string appears within the list.Using index()index() method in Python is used to find the position of a specific string in a list. It returns the index of the
2 min read
Find index of element in array in python We often need to find the position or index of an element in an array (or list). We can use an index() method or a simple for loop to accomplish this task. index() method is the simplest way to find the index of an element in an array. It returns the index of the first occurrence of the element we a
2 min read
Python - Check if Kth index elements are unique Given a String list, check if all Kth index elements are unique. Input : test_list = ["gfg", "best", "for", "geeks"], K = 1 Output : False Explanation : e occurs as 1st index in both best and geeks.Input : test_list = ["gfg", "best", "geeks"], K = 2 Output : True Explanation : g, s, e, all are uniqu
5 min read
How to Get Index of a Substring in Python? To get index of a substring within a Python string can be done using several methods such as str.find(), str.index(), and even regular expressions. Each approach has its own use case depending on the requirements. Letâs explore how to efficiently get the index of a substring.The simplest way to get
2 min read
Python - Get the indices of Uppercase characters in given string Given a String extract indices of uppercase characters. Input : test_str = 'GeeKsFoRGeeks' Output : [0, 3, 5, 7, 8] Explanation : Returns indices of uppercase characters. Input : test_str = 'GFG' Output : [0, 1, 2] Explanation : All are uppercase. Method #1 : Using list comprehension + range() + isu
5 min read