• python get first word in string (3 Ways)

    python get first word in string

    In this tutorial, we will be solving a program of python get first word in string. We will be discussing the solution to get first word in string in python in 3 ways.

    The easiest way to get the first word in string in python is to access the first element of the list which is returned by the string split() method.

    String split() method – The split() method splits the string into a list. The string is broken down using a specific character which is provided as an input parameter. The space is taken as a default separator.

    Syntax:-

    String.split(seperator)

    Python code:

    # define the string
    my_string = "Python Java Ruby JavaScript"
    
    # Using split() method
    first_word = my_string.split()[0]
    
    # Printing
    print("First word in my string is", first_word)

    Output:

    First word in my string is Python

    Method 2- Python get first word in string using for loop

    This is the simple approach, in which we will iterate over the characters of the string and concatenate the characters until we get the first occurrence of the space character.

    Python code-

    # define the string
    my_string = "Python Java Ruby JavaScript"
    
    # Using for loop
    first_word = ''
    for character in my_string:
        if character != ' ':
            first_word = first_word + character
        else:
            break
    
    # Printing
    print("First word in my string is", first_word)

    Method 3- Python get first word in string using Regex

    Regular Expression called regex is a specialized sequence of characters that helps to find a specific string or string set. Python re module provides the supports for regular expressions. To know about the re module of python you can visit here.

    Similar to Python String split() re module also has split() method which split the string at a specific pattern and return those split strings into a list.

    Syntax –

    re.split(pattern, string)

    To get first word in string we will split the string by space.  Hence the pattern to denote the space in regex is “\s”.

    Python Code-

    # import regex module
    import re
    
    # define the string
    my_string = "Python Java Ruby JavaScript"
    
    # Using regex split()
    first_word = re.split("\s", my_string)[0]
    
    # Printing
    print("First word in my string is", first_word)

    Output:

    First word in my string is Python

    Conclusion

    Above we have solved python get first word in string in 3 ways. We can get first word in string in python by using string split() method, re.split() and by using for loop.