Use the split() and if method to create a statement that prints the words that start with’s'

Asked

Viewed 181 times

0

I have the following string:

string_1 = 'Print only the words that start with s in this sentence'

and I need to use the split method and an if to output only the words started in s. But I have no idea how to do that. Help me??

  • Start using the method split. Knows how to use it?

1 answer

1


You can use the method split to separate the words in this way: string_1.split(" "). After that go through all the words in the list and check that the first element (first letter) is an "s". Example:

string_1 = 'Print only the words that start with s in this sentence'
lista_de_palavras = string_1.split(" ")
for palavra in lista_de_palavras:
    if "s" == palavra[0]:
        print(palavra)

If you want words that start with the letter "s" regardless of whether they are uppercase or lowercase, you can use the method lower() and check that the first letter is equal to lowercase "s". Example:

string_1 = 'Print only the words that start with s in this sentence'
lista_de_palavras = string_1.split(" ")
for palavra in lista_de_palavras:
    if "s" == palavra.lower()[0]:
        print(palavra)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.