Python - Print Each Sentence On New Line

2019-06-13 03:14发布

问题:

Per the subject, I'm trying to print each sentence in a string on a new line. With the current code and output shown below, what's the syntax to return "Correct Output" shown below?

Code

sentence = 'I am sorry Dave. I cannot let you do that.'

def format_sentence(sentence):
    sentenceSplit = sentence.split(".")
    for s in sentenceSplit:
        print s + "."

Output

I am sorry Dave.
 I cannot let you do that.
.
None

Correct Output

I am sorry Dave.
I cannot let you do that.   

回答1:

You can do this :

def format_sentence(sentence) :
    sentenceSplit = filter(None, sentence.split("."))
    for s in sentenceSplit :
        print s.strip() + "."


回答2:

There are some issues with your implementation. First, as Jarvis points out in his answer, if your delimiter is the first or last character in your string or if two delimiter characters are right next to each other, None will be inserted into your array. To fix this, you need to filter out the None values. Also, instead of using the + operator, use formatting instead.

def format_sentence(sentences):
    sentences_split = filter(None, sentences.split('.'))
    for s in sentences_split:
        print '{0}.'.format(s.strip())


回答3:

You can split the string by ". " instead of ".", then print each line with an additional "." until the last one, which will have a "." already.

def format_sentence(sentence):
    sentenceSplit = sentence.split(". ")
    for s in sentenceSplit[:-1]:
        print s + "."
    print sentenceSplit[-1]


回答4:

Try:

def format_sentence(sentence):
    print(sentence.replace('. ', '.\n'))