Get first word from string python

text is :

WYATT    - Ranked # 855 with    0.006   %
XAVIER   - Ranked # 587 with    0.013   %
YONG     - Ranked # 921 with    0.006   %
YOUNG    - Ranked # 807 with    0.007   %

I want to get only

WYATT
XAVIER
YONG
YOUNG

I tried :

(.*)?[ ]

But it gives me the :

WYATT    - Ranked

Nick's user avatar

Nick

4,2942 gold badges23 silver badges38 bronze badges

asked Dec 6, 2012 at 18:38

Vor's user avatar

Regex is unnecessary for this. Just use some_string.split(' ', 1)[0] or some_string.partition(' ')[0].

answered Dec 6, 2012 at 18:41

Silas Ray's user avatar

Silas RaySilas Ray

25.5k5 gold badges49 silver badges62 bronze badges

5

If you want to feel especially sly, you can write it as this:

(firstWord, rest) = yourLine.split(maxsplit=1)

This is supposed to bring the best from both worlds:

  • optimality tweak with maxsplit while splitting with any whitespace
  • improved reliability and readability, as argued by the author of the technique.

I kind of fell in love with this solution and it’s general unpacking capability, so I had to share it.

Neuron's user avatar

Neuron

4,9665 gold badges38 silver badges56 bronze badges

answered Oct 18, 2016 at 12:58

Huge's user avatar

HugeHuge

6417 silver badges14 bronze badges

4

You shoud do something like :

print line.split()[0]

answered Jan 12, 2016 at 13:52

Nado's user avatar

NadoNado

2774 silver badges7 bronze badges

3

Use this regex

^w+

w+ matches 1 to many characters.

w is similar to [a-zA-Z0-9_]

^ depicts the start of a string


About Your Regex

Your regex (.*)?[ ] should be ^(.*?)[ ] or ^(.*?)(?=[ ]) if you don’t want the space

answered Dec 6, 2012 at 18:39

Anirudha's user avatar

AnirudhaAnirudha

32.2k7 gold badges67 silver badges88 bronze badges

1

Don’t need a regex.
string[: string.find(' ')]

answered Dec 6, 2012 at 18:47

Ricardo Alvaro Lohmann's user avatar

4

You don’t need regex to split a string on whitespace:

In [1]: text = '''WYATT    - Ranked # 855 with    0.006   %
   ...: XAVIER   - Ranked # 587 with    0.013   %
   ...: YONG     - Ranked # 921 with    0.006   %
   ...: YOUNG    - Ranked # 807 with    0.007   %'''

In [2]: print 'n'.join(line.split()[0] for line in text.split('n'))
WYATT
XAVIER
YONG
YOUNG

answered Dec 6, 2012 at 18:42

Lev Levitsky's user avatar

Lev LevitskyLev Levitsky

62.7k20 gold badges146 silver badges173 bronze badges

0

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.

Method 1- Python get first word in string using split()

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

Read also: Python split string into list of characters in 4 Ways

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 support for regular expressions. To know about the re module of python you can visit here.

Similar to Python String split() re module also has a split() method which split the string at a specific pattern and returns 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.

I am Passionate Computer Engineer. Writing articles about programming problems and concepts allows me to follow my passion for programming and helping others.

get the first word in a string Python

Sometimes we come across situations where we need to get first word in string python. Hence it is often helpful to have shorthands to perform this function. This article also covers the situations where we need all words present in the string.

Method #1: Using split()

Using the split function, we can break the string into a list of words. Use str.split() and list indexing to get the first word in a string. Call str.split() to create a list of all words in str separated by space or newline character. Index the result of str.split() with [0] to return the first word in str.

Getting the first word in a string will return the first series of characters that precede a space or a newline character. For example, getting the first word in the “Tutorials Website” string returns “Tutorials.”

string = «Tutorials Website»

all_words = string.split()

first_word= all_words[0]

print(first_word)

Output:

Get first word in string python

Get the All words in a string

Getting all words in a string will return the series of characters that precede a space or a newline character. For example,

string = «Tutorials Website is the best Online Web Development Tutorials Portal»

all_words = string.split()

print(all_words)

Output:

[‘Tutorials’, ‘Website’, ‘is’, ‘the’, ‘best’, ‘Online’, ‘Web’, ‘Development’, ‘Tutorials’, ‘Portal’]

get first word in string python

Read Also: Python vs Node.JS: Which one is the best fit for your project?

Conclusion:

Using the Split function to Get first word in string python is the most generic and recommended method to perform this particular task. But the drawback is that it fails to contain punctuation marks in string cases.

Hire Best Website Designer and Developerin Delhi India

Pradeep Maurya

Pradeep Maurya is the Professional Web Developer & Designer and the Founder of  “Tutorials website”. He lives in Delhi and loves to be a self-dependent person. As an owner, he is trying his best to improve this platform day by day. His passion, dedication and quick decision making ability to stand apart from others. He’s an avid blogger and writes on the publications like Dzone, e27.co

You could make the code better (and shorter) by using regex to split any delimiters that occur in the string, for example, in Hello.world, the string (list form) would then be like ['', 'Hello', ''] (after splitting the first word from delimiters) and then you can access the first word from index [1] (always). Like this,

import re
def first_word(s):
    return re.split(r"(b[w']+b)(?:.+|$)", s)[1] 

Here are some tests:

tests = [
"Hello world",
"a word",
"don't touch it",
"greetings, friends",
"... and so on ...",
"hi",
"Hello.world",
"Hello.world blah"]

for test in tests:
    assert first_word("Hello world") == "Hello"
    assert first_word(" a word ") == "a"
    assert first_word("don't touch it") == "don't"
    assert first_word("greetings, friends") == "greetings"
    assert first_word("... and so on ...") == "and"
    assert first_word("hi") == "hi"
    assert first_word("Hello.world") == "Hello"
    assert first_word("Hello.world blah") == "Hello"
    print('{}'.format(first_word(test)))

(b[w']+b)(?:.+|$) is used above, where (b[w']+b) calls the first word of the string (in list form). b allows you to perform a «whole words only» search using a regular expression in the form of b"word"b. Note that using [w'] (instead of [w+]) leaves the apostrophe in don't. For (?:.+|$), you can take a look here.

Here are the expected outputs:

Hello
a
don't
greetings
and
hi
Hello
Hello

After timing it —

%timeit first_word(test)
>>> 1.54 µs ± 17.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

NOTE — A delimiter is a sequence of one or more characters used to specify the boundary between separate, independent regions in plain text or other data streams. An example of a delimiter is the comma character, which acts as a field delimiter in a sequence of comma-separated values.

Hope this helps!

You are here: Home / Python / Python Get First Word in String

In Python, we can easily get the first word in a string. To do so, we can use the Python split() function and then access the first element of the list of words.

string = "This is a string with words."

first_word = string.split(" ")[0]

#Output:
This

When working with strings in our Python code, it can be useful to be able to extract specific words from the string variables.

In particular, it would be useful to be able to get the first word from a string of words.

With Python, we can easily get the first word from a string.

The easiest way to get the first word from a string in Python is to use the Python split() function, and then access the first element (position “0”).

Below shows an example of how to get the first word in a string using Python.

string = "This is a string with words."

first_word = string.split(" ")[0]

#Output:
This

How to Get the Last Word of a String

In a very similar way to above, we can also get the last word of a string.

The difference between getting the first and last word in a string is that now we will be getting the last element after splitting the original string.

To get the last word from a string, we use the Python split() function and then access the “-1” position element.

Below is an example of how you can get the last word in a string using Python.

string = "This is a string with words."

last_word = string.split(" ")[-1]

#Output:
words.

Hopefully this article has been useful for you to understand how to get the first word of a string in Python.

Other Articles You’ll Also Like:

  • 1.  Get First Character of String in Python
  • 2.  Using Python to Sum the Digits of a Number
  • 3.  Golden Ratio Constant phi in Python
  • 4.  Using Python to Read Random Line from File
  • 5.  Check if Word is Palindrome Using Recursion with Python
  • 6.  Using Python to Add String to List
  • 7.  Check if a Number is Divisible by 2 in Python
  • 8.  Get Month Name from Date in Python
  • 9.  Check if File Exists in AWS S3 Bucket Using Python
  • 10.  Unset Environment Variables in Python

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Понравилась статья? Поделить с друзьями:
  • Get file list to excel
  • Give a single word
  • Give a little take a little word
  • Get external data excel
  • Give a good word for me