Home > front end >  How to add "?" sign if the sentence type is questions
How to add "?" sign if the sentence type is questions

Time:03-22

I have a list. In this list have various type of sentences suppose question type and general sentences. I want to add question mark "?" sign after end of the sentence if it it is question.

Here is my list

lst = ['what is Fame', 'how can you start work', 'can you learn design', 'this is text']

I tried this code

for i in lst:
if 'what' or 'how' or 'can' in lst:
    print(i, '?')

But not getting my desired output.

I would like to achieve:

what is Fame?
how can you start work?
can you learn design?

Could anyone please help me to do this?

Thanks, everyone!

CodePudding user response:

You can achieve the desired output by checking if sentence in list startswith with a specific word. If yes, you can print a question mark at the end:

lst = ['what is Fame', 'how can you start work', 'can you learn design', 'this is text']

for phrase in lst:
    if phrase.startswith('what') or phrase.startswith('how') or phrase.startswith('can'):
        print(phrase   '?')

CodePudding user response:

You can also make your own startswith, which is just some simple use of Python's great slicing notation.

def startswith(s, initial):
  return s[0:len(initial)] == initial

Building on Dan's answer:

def startswith(s, initial):
  return s[0:len(initial)] == initial

lst = ['what is Fame', 'how can you start work', 'can you learn design', 'this is text']

for phrase in lst:
    if startswith(phrase, 'what') or startswith(phrase, 'how') or startswith(phrase, 'can'):
        print(phrase   '?')

It is not advisable to extend the built in String with your own stuff, but it can be done.

  • Related