I am in course that uses Gaddis' Starting Out With Pyton 2nd Edition. There is a problem in the course that asks use to write a program that would capitalize sentences that a user inputs. I have come up with a reasonable solution, but I have two major problems.

The first is that we haven't started using advanced modules like re yet, so I know there is a more elementary way of doing this and second, I can't get it to capitalize proper nouns like Joe and I.

Here is what I am using.

import re

def sentCapitalizer():

    print('Today you are going to enter a random string.')
    print('The string can be any number of sentences long.')
    print('Punctuation is necessary but capitalization is not.')
    print('Perhaps how you would send a multi-sentence text message.')

    user_string = input('Enter your string: ')

    print('Here is the sentence with proper capitalization:')
    rtn = re.split('([.!?] *)', user_string)
    print(''.join([each.capitalize() for each in rtn]))


My instructor gave me a hint to utilize the upper() and replace() methods by finding the punctuations, however, I can't seem to figure out how to extract the portions of the strings. (I.e. find ".?!" then search after to determine if the next letter needs to be capitalized.)

Can someone help me with this? I've already turned in the assignment as I did it and was promised credit, but as the assignment isn't due until tommorrow, I'd really like full credit. You don't need to do an entire program, just get me headed in the right direction.


5 Years
Discussion Span
Last Post by alexgwhiz69

PS - I've searched the forums and only found the solution using the same method I did. I need the more elementary method, even if it isn't as efficient.



Please, someone, anyone, help me get my head on straight, it's due at midnight!


Here is function to find punctuation "by hand", but I won't help you more because it's homework.

text = """In 1876 the then Duke of Marlborough was appointed Viceroy and brought his son,
Lord Randolph Churchill, to reside at the Little Lodge as his Private Secretary. Lord Randolph was
accompanied by his wife, Jennie and 2 year old son, Winston. Though he only spent 4 years there
it has been claimed that the young Winston first developed his fascination with militarism from
watching the many military parades pass by the Lodge."""

def find_punctuation(s):
    positions = list()
    start = 0
    while start < len(s):
        pos = list()
        for c in (".", "!", "?"):
            p = s.find(c, start)
            if p >= start:
        if pos:
            m = min(pos)
            start = m + 1
    return positions


"""my output -->
[159, 238, 423]

Edited by Gribouillis: n/a


I already got a 100 on the assignment (how could she punish me for doing something the proper way lol), I just need to know how to do it in the more elementary way.

Here's what my teacher sent me:

Basically, we wrote this program by searching for the period . and then storing characters into a string with the period, space and next letter, and did a replace with period, space and the upper letter. Basically utilizing the .upper() and .replace() methods.

However, I have no idea how to "store the characters into a string" like she's talking about. If someone would simply show me a command to do that, I would be able to figure the rest out. My brain just isn't working the right way, here, lol.


Strings are immutable, but you can create a list of characters in the string and then process the list. Finally join the list characters to a string again.

Here is an example how to do this ...

# capitalize the sentences in a text string

text = """hello there!  my name is Frank.
could I ask you for some spare change?"""

# create a list of characters in the text
char_list = []
for c in text:

# test


# process the list of characters
# turn the leading character of each sentence to upper
lead_char = True
for ix, c in enumerate(char_list):
    if lead_char and c.isalpha():
        c = c.upper()
        # insert changed processed character into list
        char_list[ix] = c
        # set leading character flag to false
        lead_char = False
    if c in '?!.':
        lead_char = True

# join the list of characters back to a string
new_text = ''.join(char_list)

''' my result (list has been beautified) -->
['h', 'e', 'l', 'l', 'o', ' ', 't', 'h', 'e', 'r', 'e', '!', ' ', 
' ', 'm', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' ', 'F', 
'r', 'a', 'n', 'k', '.', '\n', 'c', 'o', 'u', 'l', 'd', ' ', 'I', 
' ', 'a', 's', 'k', ' ', 'y', 'o', 'u', ' ', 'f', 'o', 'r', ' ', 
's', 'o', 'm', 'e', ' ', 's', 'p', 'a', 'r', 'e', ' ', 'c', 'h', 
'a', 'n', 'g', 'e', '?']
Hello there!  My name is Frank.
Could I ask you for some spare change?

I am trying to do the same thing a bit longer way but got lost. I was originally asked to do the first capitalization of string from an entire file using len(), split(), range.. etc but don't have enough time to do it. So I came up with this for python3.2 but I've failed to figure out where I made my mistake when it says " title_case_word = word[0].upper() + word[1:] IndexError: string index out of range # Function opens file, works on the file, closes then sends to ouput" Suggestions?


Inline Code Example Here

  1. def sentence():
  2. file = open("text.txt","r")
  3. # Find string splitters (!,.,?) and capitalize first letter
  4. # of first word in string after split then join the string again.
  5. for line in file.readlines():
  6. for character in line:
  7. words = line.split('.')
  8. capitalized_words = []
  9. for word in words:
  10. title_case_word = word[0].upper() + word[1:]
  11. capitalized_words.append(title_case_word)
  12. output = '.'.join(capitalized_words)
  13. words = line.split('!')
  14. capitalized_words = []
  15. for word in words:
  16. title_case_word = word[0].upper() + word[1:]
  17. capitalized_words.append(title_case_word)
  18. output = '!'.join(capitalized_words)
  19. words = line.split('?')
  20. capitalized_words = []
  21. for word in words:
  22. title_case_word = word[0].upper() + word[1:]
  23. capitalized_words.append(title_case_word)
  24. output = '?'.join(capitalized_words)
  25. file.close()
  26. display(output)
  27. def display(output_file):




This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.