How to Extract Words From a String in Python

Python is a free, interpretive language that integrates modules from other programming languages, like C and Perl. When programming in Python, you may need to extract words from a string. For example, you may want to extract a company name from a Web address. To extract words, use the built-in Python module, "Re", to manipulate text using regular expressions. If you are familiar with the Perl programming language, you'll find that the Python "re" module is very similar to text operations in Perl.

Instructions

    • 1

      Open your Python editor.

    • 2

      Load the "re" module by typing:

      import re

    • 3

      Enter your string. For example, type:

      text = ('This is my string example.')

    • 4

      Extract words from your string by using the regular expression "findall" function. Continuing the example, type:

      re.findall (r"string", text)

      In this example, Python searches the entire string for the word, "string" in the variable, "text."

    • 5

      Press "Enter." Python returns the word as a string object in a list. Continuing the example, Python returns:

      ['string']

Related Searches:

References

Comments

Related Ads

Featured