0

I am trying to use some for loops to take a sentence and capitalize the first letter of each word.

p1 = "the cat in the hat"

def title_creator(p1):
    p = p1.split()
    p_len = len(p)
    d = []
    for i in range(p_len):
        first_letter = p[i][0]
        m = first_letter.upper()
        d.append(m)
        p[i][0] == d[i]
    p = " ".join(p)
    return p

z = title_creator(p1)
print(z)

This outputs the same original sentence from the top. How would I be able to replace an index from one list to another?

-ps I'm sorry if this problem is really easy and I'm just overlooking something simple.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
NotASuperSpy
  • 43
  • 2
  • 6

4 Answers4

5

Use title():

p1 = "the cat in the hat"

print(p1.title())
# The Cat In The Hat

EDIT:

Just incase you want to experiment with for loop you can use it like this:

p1 = "the cat in the hat"

def title_creator(p1):
    p = p1.split()
    for index, element in enumerate(p):
        p[index] = element.capitalize()
    result = " ".join(p)
    return result

z = title_creator(p1)
print(z)
Neeraj
  • 975
  • 4
  • 10
1

Almost, the problem with your original code is that you are never actually updated p (since == checks the two values are equivalent, you need single equals = to set the left to the right). Something like this would work:

def title_creator(phrase):
    words = phrase.split()
    output = []
    for word in words:
        capitalised_word = word[0].upper() + word[1:]
        output.append(capitalised_word)

    return " ".join(output)

p1 = "the cat in the hat"
z = title_creator(p1)
print(z)
domwhill
  • 93
  • 4
1

== is used for comparisons, while = is used for assignments. Additionally, strings are immutable in Python, meaning their values cannot be changed once they are created. So p[i][0] = d[i] should not work. Your options are as follows: convert each string to a list or create a new string as seen below:

p1 = "the cat in the hat"

def title_creator(p1):
    p = p1.split()
    p_len = len(p)
    for i in range(p_len):
        p[i] = p[i][0].upper() + p[i][1:]
    p = " ".join(p)
    return p

z = title_creator(p1)
print(z)

Output:

The Cat In The Hat
wjandrea
  • 28,235
  • 9
  • 60
  • 81
0

See SequenceToSequence's answer for an explanation of why your code doesn't work and Neeraj's answer for the best practical way to do what you want (BTW, you might want to read about the XY problem). I want to answer the question at face-value.

Yes, you can replace indexes, but it's not necessary when you can use a generator expression instead:

def title_creator(string):
    words = string.split()
    return ' '.join(w[0].upper()+w[1:] for w in words)

print(title_creator('the cat in the hat'))  # -> The Cat In The Hat
wjandrea
  • 28,235
  • 9
  • 60
  • 81