Home > OS >  I tried and I only printed out the letter 's's instead of the words that start with s. I&#
I tried and I only printed out the letter 's's instead of the words that start with s. I&#

Time:07-16

Use for, .split(), and if to create a Statement that will print out words that start with 's':

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

CodePudding user response:

you can use str.startswith method

st = 'Print only the words that start with s in this sentence'
for word in st.split():
    if word.startswith('s'):
        print(word)

CodePudding user response:

The .split() method splits a string into a list. Below is my attempt at printing the words that begin with s using split() and a for loop.

The for loop goes through each word in the list, if the letter "s" is in the first index (first letter) of the word, print that word.

st = "Print only the words that start with s in this sentence"
string_into_list = st.split()

for word in string_into_list:
    if "s" in word[0]:
        print(word)

Hopefully this helps :)

CodePudding user response:

Split the list into Strings with .split(). Use " " as a separator because you want spaces to separate the words.

st = "Print only the words that start with s in this sentence"
words = []
for word in st.split(" "):
    if word.startswith("s"):
        words.append(word)

print(words)
  • Related