Python - Print Each Sentence On New Line

不问归期 提交于 2019-12-10 11:56:45

问题


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'))


来源:https://stackoverflow.com/questions/42167881/python-print-each-sentence-on-new-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!