Python – Separate first word from String

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output :

The original string is : gfg is best
Initial word separated list : ['gfg', 'is best']



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : nidhi_biet

Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.