This is python code and I am new to programming and I can't get just the first word of the sentence to capitalize.

def main():
    

    input= 'the money is in the bag. however you dont want it.'
    words = input.split('.')
    capitalized_words = []
    for word in words:
        word=word.strip()
        title_case_word = words[0].upper()
        capitalized_words.append(title_case_word)
    output = '.'.join(capitalized_words)
    print(output)
    
 
main()

it is returning:
>>>
THE MONEY IS IN THE BAG.THE MONEY IS IN THE BAG.THE MONEY IS IN THE BAG
>>>

Can anyone help???

Dani AI

Generated

Short diagnosis: the loop in your original code always uses words[0] (so you keep reusing the first slice) and upper() makes the entire piece uppercase. Also avoid using the name input (it shadows the builtin) — 's suggestion to add print statements is a good way to spot that. was right to warn about the builtin name.

A compact, robust way to capitalise only the first alphabetic character of each sentence (preserving the rest of the sentence exactly) is to use a single regex substitution that finds the start of the string or a sentence-ending marker, any intervening whitespace, then the first lowercase letter and uppercases that one letter:

import re

def sentence_case(text):
    # match start or a punctuation immediately before the word, allow any spaces,
    # then capture the first lowercase letter to uppercase it
    pattern = re.compile(r'(^|(?<=[.!?]))(\s*)([a-z])')
    return pattern.sub(lambda m: m.group(1) + m.group(2) + m.group(3).upper(), text)

s = 'the money is in the bag.  however you dont want it.'
print(sentence_case(s))

This preserves internal capitalization (so proper nouns are not lowercased the way str.capitalize() would). Caveats: abbreviations like "Mr." or "e.g." can look like sentence boundaries; handling those reliably requires sentence tokenization (for example with NLTK or spaCy) rather than a simple regex. If you only want the whole first word uppercased instead of just its first letter, capture the word and apply .upper() or .capitalize() to that group in the replacement.

Recommended Answers

All 7 Replies

Use print statements to track what happens

def main():
    

    input= 'the money is in the bag. however you dont want it.'
    words = input.split('.')
    capitalized_words = []
    for word in words:
        word=word.strip()
        print(words[0])
        title_case_word = words[0].upper()
        capitalized_words.append(title_case_word)
        print(capitalized_words)
    output = '.'.join(capitalized_words)
    print(output)
    
 
main()

Output:

the money is in the bag
['THE MONEY IS IN THE BAG']
the money is in the bag
['THE MONEY IS IN THE BAG', 'THE MONEY IS IN THE BAG']
the money is in the bag
['THE MONEY IS IN THE BAG', 'THE MONEY IS IN THE BAG', 'THE MONEY IS IN THE BAG']
THE MONEY IS IN THE BAG.THE MONEY IS IN THE BAG.THE MONEY IS IN THE BAG

Dont use input as a varible name,is reserved word for user input.
To simpilfy it,there is capitalize string method.

>>> s = 'the money is in the bag. however you dont want it.'
>>> [i.capitalize() for i in s.split()]
['The', 'Money', 'Is', 'In', 'The', 'Bag.', 'However', 'You', 'Dont', 'Want', 'It.']

You can of course use upper() method and take out first word[0] in same way.
list comprehensions as i use is very common is python,so you better learn right away.
Try to break it up and write is an ordinary loop,to understand it.

import re

def sentCapitalizer():

    s = 'the money is in the bag. however you dont want it.'

   rtn = re.split('([.!?] *)', s)
    print('')
    print(''.join([each.capitalize() for each in rtn]))
    

sentCapitalizer()

Returns

[The money is in the bag. However you dont want it.]

I think you're in the same class that I am! Don't use the answer I gave, then! I was just checking these forums for a little help myself, saw that you needed something similar to me, and then provided an answer. Then I saw your location and was like OH GOODNESS. I will look up the rules on students collaborating together, perhaps we can help each other before the day is over with.

You have to test for more than a period unless you know the sentences won't contain abbreviations. Take a look at this variation:

import re

def sentCapitalizer():
    s = 'the money is in the bag Mr. Jones. however you dont want it.'

    rtn = re.split('([.!?] *)', s)
    print('')
    print(''.join([each.capitalize() for each in rtn]))

sentCapitalizer()

thanks for that

although there is one issue with this in that it doesn't return proper nouns (Joe, I) back capitalized

any suggestions?

ALSO, if this guys is indeed in the same class I am, this solution won't even work lol

This touches only first letter of each sentence and looks also '?!' a la Monsieur Gribouillis:

def cap_first_alnum(sent):
    for ind in range(len(sent)):
            if sent[ind].isalnum():
                #print ind, sent[ind], repr(sent)
                return sent[:ind] + sent[ind].upper() + sent[ind+1:]
    return sent

def cap_sentences(paragraph):
    for sep in '.!?':
        paragraph = sep.join(cap_first_alnum(sent) for sent in paragraph.split(sep)) if sep in paragraph else paragraph
    return paragraph

print cap_sentences("the money is in the bag, Jack! sure it is. is it not? however you don't want it.")
print cap_sentences('only words in sequence')
print cap_sentences('123434 can not capitalize!')

"""Output:
The money is in the bag, Jack! Sure it is. Is it not? However you don't want it.
only words in sequence
123434 can not capitalize!
"""

Again one more thing learned in string operations, I did not know that capitalize method was not clever enough to skip non-letters.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.