0

Hi I am trying to create a function that capitalises a phrase so that it meets APA format i.e doesn't capitalise any unimportant words like a, an etc But I can't get it to work. I am a novice programmer so any tips would be appreciated. Below is my code:

def capitalise(phrase):
    # your code goes here to perform the word capitalisation
    p = str(phrase)
    v = p.split()

    for x in v:
        if x != "a" or x != "an" or x != "the" or x != "am" or x != "is" or x != "are" or x != "and" or x != "of" or x != "In" or x != "on" or x != "with" or x != "from" or x != "to":
            x.title()

print(x)
Glrs
  • 1,060
  • 15
  • 26
m.linus
  • 11
  • 1
  • 6

2 Answers2

0

A simple example:

unimportant=["a", "an", "the", "am" ,"is", "are", "and", "of", "in" , "on", "with", "from", "to"]


def capitalise(phrase):
    # your code goes here to perform the word capitalisation
    resp=""
    v = phrase.split()
    for x in v:
        if x not in unimportant:
            resp += (" " + x.title())
        else:
            resp += (" " + x)

    return resp

print(capitalise("This is an exeample of title"))

Result:

This is an Exeample of Title
Shoo Limberger
  • 277
  • 2
  • 11
  • Instead of appending an empty space to the beginning of each word it would be better to just append each word to an empty list (`resp += [x.title()]`), and then join the list when calling the return statement (i.e. `return ' '.join(resp)`) so that you don't have the leading space at the beginning of the final string. Either that, or use `return resp[1:]` or `strip()` to trim that leading space. – Benji A. Feb 11 '20 at 10:13
0
def capitalise(phrase): 

    doNotCap = ["a", "an", "the", "am", "is", "are", "and", "of", "in" ,"on" ,"with" ,"from" ,"to"]
    parts = phrase.split()    

    # join stuff together using ' ' which was removed by split() above
    # use a ternary to decide if something needs capitalization using .title()
    # if it is in doNotCap: use as is, else use v.title()
    return ' '.join( v if v in doNotCap else v.title() for v in parts)

k = "this is a kindof trivial test sentence to show that some words like a an the am is are and of in on with from to are not capitalized."


print(k)
print()
print(capitalise(k))

Output:

this is a kindof trivial test sentence to show that some words like a an the am is are and of in on with from to are not capitalized.

This is a Kindof Trivial Test Sentence to Show That Some Words Like a an the am is are and of in on with from to are Not Capitalized.
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69