Capitalise program

Many people do not use capital letters correctly, especially when typing on small
devices like smart phones. To help address this situation, you will create a function
that takes a string as its only parameter and returns a new copy of the string that has
been correctly capitalized. In particular, your function must:
• Capitalize the first non-space character in the string,
• Capitalize the first non-space character after a period, exclamation mark or question
mark, and
• Capitalize a lowercase “i” if it is preceded by a space and followed by a space,
period, exclamation mark, question mark or apostrophe.
Implementing these transformations will correct most capitalization errors. For
example, if the function is provided with the string “what time do i have to be there?
what’s the address? this time i’ll try to be on time!” then it should return the string
“What time do I have to be there? What’s the address? This time I’ll try to be on
time!”. Include a main program that reads a string from the user, capitalizes it using
your function, and displays the result.

This is the question

And the answer code given is below, by the creator of the exercise, as l couldn’t do it.

# Improve the capitalization of a string.
## Capitalize the appropriate characters in a string
# @param s the string that needs capitalization
# @return a new string with the capitalization improved
def capitalize(s):
    # Create a new copy of the string to return as the function’s result
    result = s
    # Capitalize the first non-space character in the string
    pos = 0
    while pos < len(s) and result[pos] == "   ":
        pos = pos + 1
    if pos < len(s):
        # Replace the character with its uppercase version without changing any other characters
        result = result[0: pos] + result[pos].upper() + result[pos + 1: len(result)]
        return result
    # Capitalize the first letter that follows a ‘‘.’’, ‘‘!’’ or ‘‘?’’
    pos = 0
    while pos < len(s):
        if result[pos] == "." or result[pos] == "!" or \
                result[pos] == "?":
            # Move past the ‘‘.’’, ‘‘!’’ or ‘‘?’’
            pos = pos + 1
        # Move past any spaces
            while pos < len(s) and result[pos] == " ":
                pos = pos + 1
        # If we haven’t reached the end of the string then replace the current character
        # with its uppercase equivalent
            if pos < len(s):
                result = result[0: pos] + \
                result[pos].upper() + \
                result[pos + 1: len(result)]
        # Move to the next character
        pos = pos + 1

    # Capitalize i when it is preceded by a space and followed by a space, period, exclamation
    # mark, question mark or apostrophe
    pos = 1
    while pos < len(s) - 1:
        if result[pos - 1] == " " and result[pos] == "i" and \
                (result[pos + 1] == " " or result[pos + 1] == "." or \
                 result[pos + 1] == "!" or result[pos + 1] == "?" or \
                 result[pos + 1] == "’"):
            # Replace the i with an I without changing any other characters
            result = result[0: pos] + "I" + result[pos + 1: len(result)]
        pos = pos + 1
    return result

# Demonstrate the capitalize function
def main():
    s = input("Enter some text: ")
    capitalized = capitalize(s)
    print("It is capitalized as:", capitalized)

# Call the main function

now, l have a few issues:

  1. This code is not doing the job, I don’t know if it has an error?
  2. How to debug a program in a function, normally we can put print statements in a normal code, where ever we want to see the output, so in a function, to understand what each part of the code outputs, what can l do?


You just described one of the good routes to debugging, print, threre’s nothing stopping you from performing the same thing here. When the function is called the print statements are executed like they normally would be.

For some slightly more advanced tools Python has it’s own built-in debugging library pdb pdb — The Python Debugger — Python 3.9.5 documentation which is decent for some problems where you want to drop into an interactive session but it is quite minimal. You’d likely have powerful debugging tools with whatever code editor you’re using too. From a previous question I believe you’re working with PyCharm? Have a look at their docs on debugging as there are some very useful options available there.

1 Like

I kind of get confused about the print and return statement when using functions, that is why l was asking?

Ahh I think I may have misinterpreted your comment from another thread as a solved problem. The print function has no special properties when it comes to user defined functions. Returning something from a function however, is an inherent part of a function (ignoring generators and such). Even if an actual return statement is not executed in the function, the function will still return an object (by default it returns the None) object.

def func(): print("something") print("something else") return 3 print("this is not printed!") x = func() # the first two print statements still execute # they then dump strings to the console # the function return, however, is assigned to x # the final print is never executed at all! print(x) # We can use this object as we wish

Print is just a method of outputting strings somewhere, typically to the console. You can have as many print statements in a function as you like. If a return statement is executed then an object is passed back to the caller and the function exits at that point.

1 Like

by object you mean a result is given?

so a return statement has two uses:

  1. an object is passed back to a caller and
  2. it is a way of exiting a function

sometimes l wonder how people create such programs, what should l do such that if l am told to write the same program, l can write it

You can call it a result if you like but since it’s Python you’d be passing an object reference (if that doesn’t mean much to you then either now or later it may be worth looking into python’s objects).

Yes, those uses sum it up quite nicely, for the second you’ll find some functions return is used to exit the function at a specific point e.g. an if statement returns a value and stops any further execution.

As for creating it, a good place to start is pen and paper or similar and just map out how you would do this without code. Like what would be the physical process of solving this problem. You’d want to start reading a string, then you’d want to find specific characters etc. etc.

Breaking the whole thing into little steps first and making sure you can solve those is also helpful. As with that earlier process mapped out, task1 is to read in a string, task2 might be to find specific characters. Solving the problem is the main goal, you can worry about efficiency and clarity afterwards when refactoring. The more you practice this process, the more well-written code you read and tutorial you follow the easier the whole thing becomes. Both learning from the code and guidance of others and implementing your own are important; it’s a slow and steady improvement.

Relax a bit and don’t judge yourself by what someone with years of experience can achieve, smart small, create working code that you understand completely. Be willing to take criticism on the road to improvement; in time you’ll be ready to defend your own process but to do so you must understand your own code; blindly copy/pasting more effective solutions can hamper your own learning. If you do find a more effective option focus on learning the ins and outs of how and why it works before implementing it.

1 Like

Like l don’t understand how this works? Or how they came up with it

Since it was mentioned earlier why not print the output of those three slices (or 4 if you want the result too).

The more confused I get, the more prints I put in. :laughing:
If you have to use multiple prints, you start having to get more verbose with them:
print(f"while loop 1: {pos}: {result[pos]}")

1 Like

ya did that, broke them down separate, and saw the output, nice code :grinning:

1 Like

not sure how your code works, not still used to f’strings

variable = "something I might change"

print("This is " + variable)
print(f"This is {variable}")
print("This is {0}".format(variable))
print("This is {variable}".format(variable=variable))

All of these output: This is something I might change
While I was checking to make sure I wasn’t making a mistake in the sandbox the second one stopped working for some reason. It works in VSC and it has worked in my courses.

1 Like

It’s possible that the “sandbox” was using Python2 rather than Python3. You can check the version like so:

import sys print(sys.version) message = "Hello World!" print(f"My message to the world is, '{message}'")

Yeah, that was the issue. I thought I’d used f strings in there before but I could be mistaken.
Screenshot from 2021-05-21 16-27-38


There is a Python3 sandbox available as well. Just add 3 to the end of the url in your screenshot.


Hi Bavarcus,

Why are you using sandbox, I didn’t know what sandbox was, so l googled and found it is used to test potentially any malicious software

It’s also a learning tool, I was using it before I installed vsc so sometimes I put code in there rather than starting the local program. It seems more convenient when I’m copying code out of forums to try to help out.