Open In App

Python – Separate first word from String

Last Updated : 15 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We need to write a Python program to split a given string into two parts at the Kᵗʰ occurrence of a specified character. If the character occurs fewer than K times, return the entire string as the first part and an empty string as the second part. Separating the first word from a string involves identifying and extracting the substring that appears before the first space or delimiter. This can be efficiently done using methods like split() or partition() which split the string at spaces or specific characters, allowing us to isolate the first word.

Using split()

split() method divides the string into words (by whitespace by default) and returns a list. The first element of the list will be the first word.

Python
s1 = "Hello, this is a sample string."

# Split the string and get the first word
s2 = s1.split()[0]

print(s2) 

Output
Hello,

Explanation: split() by default, split() splits the string based on spaces, so it will create a list of words. The first word will be at index 0 of the list.

Using partition()

We can also use the partition() method, which splits the string into three parts: everything before the first occurrence of the separator (space), the separator itself, and everything after it.

Python
s1 = "Hello, this is a sample string."

# Partition the string at the first space
s2, _, _ = s1.partition(" ")

print(s2)  

Output
Hello,

Explanation: partition() splits the string into three parts based on the first occurrence of the specified separator (in this case, a space). first part is the first word, which can be directly accessed

Using Regular Expressions (re)

We can also use regular expressions to extract the first word in a more flexible way (especially if the definition of “word” is more complex).

Python
import re

s1 = "Hello, this is a sample string."

# Use regex to match the first word
s2 = re.match(r'\S+', s1).group()

print(s2)  

Output
Hello,

Explanation:

  • re.match(r'\S+', s): This regex pattern \S+ matches the first non-space sequence of characters (i.e., the first word).
  • .group(): Extracts the matched substring, which is the first word


Next Article
Practice Tags :

Similar Reads