Greg
Greg

Reputation: 29

Python - Print Each Sentence On New Line

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.   

Upvotes: 0

Views: 7486

Answers (4)

Yihe
Yihe

Reputation: 4234

Try:

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

Upvotes: 0

Jackson Lenhart
Jackson Lenhart

Reputation: 640

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]

Upvotes: 0

Woody1193
Woody1193

Reputation: 7980

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

Upvotes: 0

Jarvis
Jarvis

Reputation: 8564

You can do this :

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

Upvotes: 3

Related Questions