简体   繁体   中英

Python find a specific word

I am trying to find if a string matches the word 'for'

str = 'foreign'
re.findall(r'for', str) 

the above code outputs ['for'], but that's not what i'm looking for. Perhaps I must use re.match, but I am not sure. Any help will be appreciated!

Use \\b to mark the border of some word:

In [782]: s = 'foreign, for fore'

In [783]: re.findall(r'\bfor\b', s)
Out[783]: ['for']

From the docs :

\\b is an assertion that the current position is located at a word boundary

Do you just want to check if the string contains the word or part of it? the pythonic way to do it is:

In [15]: s = 'foreign, for fore'

In [16]: 'for' in s
Out[16]: True

You want to get a boolean? How about bool(re.findall(r'for', str)) ? (By the way, an if statement would do that implicitely, so if re.findall(r'for', str): is ok).

If you don't need to use a regexp, you can also use: 'for' in str (which “returns” a boolean).

If you insist on using regex to check if a substring is in a string, try:

>>> import re
# If input is a sentence
>>> s = "foreign"
>>> substr = r"for"
>>> [i for i in s.split() if re.findall(substr,i)]
['foreign']

>>> s = "forex is a foreign concept ."
>>> [i for i in s.split() if re.findall(substr,i)]
['forex', 'foreign']

# If input is a list of words
>>> s = ['forex', 'is', 'a', 'foreign', 'concept', '.']
>>> [i for i in s if re.findall(substr,i)]
['forex', 'foreign']

If you want to check the existence of a substring in a string and return the string:

>>> s = "foreign"
>>> substr = "for"
>>> [i for i in s.split() if substr in s]
['foreign']

If you want to check the existence of a substring in a string and return a boolean:

>>> s = "foreign"
>>> substr = "for"
>>> substr in s
True
>>> "for" in "foreign"
True

Of course, trying to ask python in natural language is wont work:

>>> "for" in "foreign"
True
>>> is "for" in "foreign" ?
  File "<stdin>", line 1
    is "for" in "foreign" ?
     ^
SyntaxError: invalid syntax

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM