Python – Word starting at Index
Sometimes, while working with Python, we can have a problem in which we need to extract the word which is starting from a particular index. This can have a lot of applications in school programming. Let’s discuss certain ways in which this task can be performed.
Method #1: Using a loop
This is a brute-force way in which this task can be performed. In this, we iterate for the string after getting the index till the first space.
Python3
test_str = "gfg is best for geeks"
print ( "The original string is : " + test_str)
K = 7
res = ''
for idx in range (K, len (test_str)):
if test_str[idx] = = ' ' :
break
res + = test_str[idx]
print ( "Word at index K : " + str (res))
|
Output :
The original string is : gfg is best for geeks
Word at index K : best
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2: Using split() + list slicing
This is one of the ways in which this task can be performed. In this, list slicing is used to extract all characters after K, and split is used to extract the first word amongst them.
Python3
test_str = "gfg is best for geeks"
print ( "The original string is : " + test_str)
K = 7
res = test_str[K:].split()[ 0 ]
print ( "Word at index K : " + str (res))
|
Output :
The original string is : gfg is best for geeks
Word at index K : best
Time Complexity: O(n)
Auxiliary Space: O(n)
Last Updated :
05 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...