Convert UPPERCASE string to sentence case in Python

Python

Python Problem Overview


How does one convert an uppercase string to proper sentence-case? Example string:

"OPERATOR FAIL TO PROPERLY REMOVE SOLID WASTE"

Using titlecase(str) gives me:

"Operator Fail to Properly Remove Solid Waste"

What I need is:

"Operator fail to properly remove solid waste"

Is there an easy way to do this?

Python Solutions


Solution 1 - Python

Let's use an even more appropriate function for this: string.capitalize

>>> s="OPERATOR FAIL TO PROPERLY REMOVE SOLID WASTE"
>>> s.capitalize()
'Operator fail to properly remove solid waste'

Solution 2 - Python

This will work for any sentence, or any paragraph. Note that the sentence must end with a . or it won't be treated as a new sentence. (Stealing .capitalize() which is the better method, hats off to brianpck for that)

a = 'hello. i am a sentence.'
a = '. '.join(i.capitalize() for i in a.split('. '))

Solution 3 - Python

In case you need to convert to sentence case a string that contains multiple sentences, I wrote this function:

def getSentenceCase(source: str):
    output = ""
    isFirstWord = True

    for c in source:
        if isFirstWord and not c.isspace():
            c = c.upper()
            isFirstWord = False
        elif not isFirstWord and c in ".!?":
            isFirstWord = True
        else:
            c = c.lower()

        output = output + c

    return output

var1 = """strings are one of the most commonly used
data types in almost every programming language. it
allows you to store custom data, your options, and more.
IN FACT, THIS ANNOUNCEMENT IS A SERIES OF STRINGS!"""

print(getSentenceCase(var1))
# Expected output:
# Strings are one of the most commonly used
# data types in almost every programming language. It
# allows you to store custom data, your options, and more.
# In fact, this announcement is a series of strings!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMoreScratchView Question on Stackoverflow
Solution 1 - PythonbrianpckView Answer on Stackoverflow
Solution 2 - PythonZizouz212View Answer on Stackoverflow
Solution 3 - PythonEarleeView Answer on Stackoverflow