Sometimes, while working with Python strings, we can have a problem in which we need to separate the first word from the entire string. This can have possible applications in many domains such as day-day and web-development. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loop
This is the brute force way in which this task can be performed. In this, we iterate the string and extract the word till the 1st word and then append other string as other elements of list.
# Python3 code to demonstrate working of # Separate first word from String# Using loop # initializing stringtest_str = "gfg is best" # printing original stringprint("The original string is : " + test_str) # Separate first word from String# Using loopres = []temp = ''flag = 1for ele in test_str: if ele == ' ' and flag: res.append(temp) temp = '' flag = 0 else : temp += eleres.append(temp) # printing result print("Initial word separated list : " + str(res)) |
The original string is : gfg is best Initial word separated list : ['gfg', 'is best']
Method #2 : Using split()
This is recommended and a one-liner that can be used to perform this task. In this, we just split the string by space and then construct the list of separated words.
# Python3 code to demonstrate working of # Separate first word from String# Using split() # initializing stringtest_str = "gfg is best" # printing original stringprint("The original string is : " + test_str) # Separate first word from String# Using split()res = test_str.split(' ', 1) # printing result print("Initial word separated list : " + str(res)) |
The original string is : gfg is best Initial word separated list : ['gfg', 'is best']
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


