Reputation: 3083
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?
Upvotes: 64
Views: 60645
Reputation: 358
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!
Upvotes: 2
Reputation: 4998
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('. '))
Upvotes: 13
Reputation: 8254
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'
Upvotes: 110