Python - Print Each Sentence On New Line

2019-06-13 03:26发布

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.   

4条回答
放荡不羁爱自由
2楼-- · 2019-06-13 03:52

You can do this :

def format_sentence(sentence) :
    sentenceSplit = filter(None, sentence.split("."))
    for s in sentenceSplit :
        print s.strip() + "."
查看更多
时光不老,我们不散
3楼-- · 2019-06-13 03:56

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]
查看更多
Melony?
4楼-- · 2019-06-13 04:03

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())
查看更多
倾城 Initia
5楼-- · 2019-06-13 04:17

Try:

def format_sentence(sentence):
    print(sentence.replace('. ', '.\n'))
查看更多
登录 后发表回答