Back to Freecodecamp

Challenge 202: Add Punctuation

curriculum/challenges/english/blocks/daily-coding-challenges-python/698a1a73ade5ac0e19180fa5.md

latest2.0 KB
Original Source

--description--

Given a string of sentences with missing periods, add a period (".") in the following places:

  • Before each space that comes immediately before an uppercase letter
  • And at the end of the string

Return the resulting string.

--hints--

add_punctuation("Hello world") should return "Hello world."

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(add_punctuation("Hello world"), "Hello world.")`)
}})

add_punctuation("Hello world It's nice today") should return "Hello world. It's nice today."

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(add_punctuation("Hello world It's nice today"), "Hello world. It's nice today.")`)
}})

add_punctuation("JavaScript is great Sometimes") should return "JavaScript is great. Sometimes."

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(add_punctuation("JavaScript is great Sometimes"), "JavaScript is great. Sometimes.")`)
}})

add_punctuation("A b c D e F g h I J k L m n o P Q r S t U v w X Y Z") should return "A b c. D e. F g h. I. J k. L m n o. P. Q r. S t. U v w. X. Y. Z."

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(add_punctuation("A b c D e F g h I J k L m n o P Q r S t U v w X Y Z"), "A b c. D e. F g h. I. J k. L m n o. P. Q r. S t. U v w. X. Y. Z.")`)
}})

add_punctuation("Wait.. For it") should return "Wait... For it."

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(add_punctuation("Wait.. For it"), "Wait... For it.")`)
}})

--seed--

--seed-contents--

py
def add_punctuation(sentences):

    return sentences

--solutions--

py
def add_punctuation(sentences):
    result = ""
    length = len(sentences)

    for i, c in enumerate(sentences):
        if c == " " and i + 1 < length and sentences[i + 1].isupper():
            result += "."
        result += c

    if not result.endswith("."):
        result += "."

    return result