Open In App

Python – Access element at Kth index in given String

Last Updated : 05 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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))


Output

The 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))


Output

The 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

  1. Initialize the string variable test_str with a string of your choice.
  2. Initialize the integer variable K with the index of the element you want to access.
  3. 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.
  4. 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))


Output

The 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:

  1. Initialize the string test_str and Kth index K value.
  2. Convert the character at the Kth index into its ASCII value using the ord() function.
  3. Return the character representation of the ASCII value obtained in step 2 using the chr() function.
  4. 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))


Output

The original string is : geeksforgeeks
Kth index element : r

Time Complexity: O(1)
Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads