Skip to content
Related Articles

Related Articles

Python – Separate first word from String
  • Last Updated : 30 Jun, 2020

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 string
test_str = "gfg is best"
  
# printing original string
print("The original string is : " + test_str)
  
# Separate first word from String
# Using loop
res = []
temp = ''
flag = 1
for ele in test_str:
    if ele == ' ' and flag:
        res.append(temp)
        temp = ''
        flag = 0
    else :
        temp += ele
res.append(temp)
                      
# printing result 
print("Initial word separated list : " + str(res)) 
Output :
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 string
test_str = "gfg is best"
  
# printing original string
print("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)) 
Output :
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

My Personal Notes arrow_drop_up
Recommended Articles
Page :