Sunday, October 6, 2024
Google search engine
HomeLanguagesPython – Word starting at Index

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




# Python3 code to demonstrate working of
# Word starting at Index
# Using loop
 
# initializing string
test_str = "gfg is best for Lazyroar"
 
# printing original string
print("The original string is : " + test_str)
 
# initializing K
K = 7
 
# Word starting at Index
# Using loop
res = ''
for idx in range(K, len(test_str)):
    if test_str[idx] == ' ':
        break
    res += test_str[idx]
 
# printing result
print("Word at index K : " + str(res))


Output : 

The original string is : gfg is best for Lazyroar
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




# Python3 code to demonstrate working of
# Word starting at Index
# Using split() + list slicing
 
# initializing string
test_str = "gfg is best for Lazyroar"
 
# printing original string
print("The original string is : " + test_str)
 
# initializing K
K = 7
 
# Word starting at Index
# Using split() + list slicing
res = test_str[K:].split()[0]
 
# printing result
print("Word at index K : " + str(res))


Output : 

The original string is : gfg is best for Lazyroar
Word at index K : best

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

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments