Python Extract words from a given string

| | | | | | | | | | | | | | | | | | |

Method # 1: Using split()
Using the split function, we can split a string into a list of words, and this is the most common and recommended method if someone wants to complete this specific task. But the downside is that it doesn’t work in cases where the string contains punctuation marks.

# Python3 code to demonstrate
# to extract words from string
# using split()

# initializing string
test_string = "Python.Engineering is best Computer Science Portal"

# printing original string
print ("The original string is : " + test_string)

# using split()
# to extract words from string
res = test_string.split()

# printing result
print ("The list of words is : " + str(res))

Output:

The original string is: Python.Engineering is best Computer Science Portal
The list of words is: [’Python.Engineering’,’ is’, ’best’, ’Computer’, ’Science’, ’Portal’]

How to extract a word from a string in Python

How to extract a word from a string in Python

Method # 2: Using regex (findall ())
In cases that contain all special characters and punctuation marks, as discussed above, tr The traditional method of searching for words in a string using splitting can fail and therefore requires regular expressions to accomplish this task. The findall function returns a list after filtering the string and extracting words, ignoring punctuation marks.

# Python3 code to demonstrate
# to extract words from string
# using regex( findall() )
import re

# initializing string
test_string = "Python.Engineering, is best @# Computer Science Portal.!!!"

# printing original string
print ("The original string is : " + test_string)

# using regex( findall() )
# to extract words from string
res = re.findall(r’w+’, test_string)

# printing result
print ("The list of words is : " + str(res))

Output:

The original string is: Python.Engineering, is best @ # Computer Science Portal. !!!
The list of words is: [’Python.Engineering’, ’is’, ’best’, ’Co mputer ’,’ Science ’,’ Portal ’]

>Extracting a word from a string in Python

Method # 3: Using regex () + string.punctuation
This method also used regular expressions, but the get all punctuation string function is used to ignore all punctuation and get the filtered result string.

# Python3 code to demonstrate
# to extract words from string
# using regex() + string.punctuation
import re
import string

# initializing string
test_string = "Python.Engineering, is best @# Computer Science Portal.!!!"

# printing original string
print ("The original string is : " + test_string)

# using regex() + string.punctuation
# to extract words from string
res = re.sub(’[’+string.punctuation+’]’, ’’, test_string).split()

# printing result
print ("The list of words is : " + str(res))

Output:

The list of words is: [’Python.Engineering’, ’is’, ’best’, ’Computer’, ’Science’, ’Portal’]

Getting the first word from a string

I study Python, there is a problem - to receive the first word from a line. The string may start with spaces, dots, etc. ("….example, strings"). We need a function that will return the word "example". My code in which I managed to get the word, but I can’t get rid of the comma:

will print "Hello", but if the string is "Hello, world" then it will print "world"

In this approach, all words will be found:

>>> import re
>>> word = ’.... example, string’
>>> pattern = re.compile(r’w+’)
>>> pattern.findall(word)[0]
’example’


In this, only the first match:

>>> pattern.search(word).group()
’example’


Example without regular expressions:

>>> for i in word:
...     if not i.isalpha() and i != ’ ’:
...             word = word.replace(i, ’’)
...
>>> word
’ example string’
>>> word.split()[0].strip()
’example’

Shop

Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best laptop for development

$499+
Gifts for programmers

Best laptop for Cricut Maker

$299+
Gifts for programmers

Best laptop for hacking

$890
Gifts for programmers

Best laptop for Machine Learning

$699+
Gifts for programmers

Raspberry Pi robot kit

$150

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically