-2

so I'm trying to be able to detect only "astro" (case insensitive) in a sentence with other words that contain the word "astro" in it. For example:

message = 'Astro, the astronaut, studies astrology.'

if 'astro' in message:
    count = message.count('astro')
    print(count)

The output of this current code would be 3 because there are three words that contain that word in it, but I want the desired output to be 1; the first word. Any help would be greatly appreciated, thanks!

2 Answers2

0

You need to split the message into separate words using split, and then use startswith to check if astro occurs at the start of the word.

sjf
  • 785
  • 1
  • 8
  • 19
0

You need to massage the data a little bit.

message = "Astro, the astronaut, studies astrology."

First, you need to get rid of everything that's not relevant to individual words.

import string

valid = ' ' + string.ascii_lowercase
message = [char for char in message.lower() if char in valid]
message = ''.join(message)

Now, message looks a little different:

>>> message
'astro the astronaut studies astrology'

Just re-split the message on spaces and count the occurrences!

>>> message.split().count('astro')
1
blakev
  • 4,154
  • 2
  • 32
  • 52