Home > OS >  what can i do to find the sentence that only contains 'take'?
what can i do to find the sentence that only contains 'take'?

Time:05-01

i want to find all the sentence with the word 'take' in this list (x), but one of output is 'Own your mistakes before the Council'. What can I do if I only want the sentence containing 'take' instead of some words that have take inside? Thank you!!

this is my code:

x =['Own your mistakes before the Council,', "You guys know I wouldn't take you on a job you couldn't handle, right?", "Maybe just don't take Powder next time.", "You don't understand what's at stake.", 'You may take your son home, Mrs. Talis,', '- Did they take anything dangerous?', 'Do whatever it takes.', "I'll take the strongest shit you got."]
for i in x:
    if 'take'in i:
        print(i)

CodePudding user response:

Add spaces around "take", so " take ", or spilt the lines and check if it contains "take". As explained by @SUTerliakov, my first suggestion won't work all the time.

This is what the code might look like for my second suggestion.

sentences =['Own your mistakes before the Council,', "You guys know I wouldn't take you on a job you couldn't handle, right?", "Maybe just don't take Powder next time.", "You don't understand what's at stake.", 'You may take your son home, Mrs. Talis,', '- Did they take anything dangerous?', 'Do whatever it takes.', "I'll take the strongest shit you got."]

for sentence in sentences:
    words = sentence.lower().split()
    if "take" in words:
        print(sentence)

CodePudding user response:

Just to make this discussion complete, this solution will hopefully catch all take occurrences ignoring case:

import re
# Can use one-liner, but cached will work faster in a loop
regex = re.compile(r'\btake\b')
sentences = [
    'Own your mistakes before the Council,', 
    "You guys know I wouldn't take you on a job you couldn't handle, right?",
    "Maybe just don't take Powder next time.",
    "You don't understand what's at stake.",
    'You may take your son home, Mrs. Talis,',
    '- Did they take anything dangerous?',
    'Do whatever it takes.',
    "I'll take the strongest shit you got.",
    'Take this!',
]
for sentence in sentences:
    if regex.search(sentence.lower()):  # Remove .lower() to be case-sensitive
        print(sentence)

Will print

You guys know I wouldn't take you on a job you couldn't handle, right?
Maybe just don't take Powder next time.
You may take your son home, Mrs. Talis,
- Did they take anything dangerous?
I'll take the strongest shit you got.
Take this!

CodePudding user response:

Very simple, using find() method in string class:

if (i.find('take') != -1):
    print ("Contains given substring ")
else:
    print ("Doesn't contains given substring")
  • Related