0

I am trying to get this loop to capitalize each word using the capitalize() function

Here is the code

def cap(words):
  for j in words:
    print(j)
    return j.capitalize()

s = "my name"
parts = s.split(" ")
print(parts)
it = iter(parts)

capped = cap(parts)
print(capped)

result = capped.join(" ")

print(capped)

Output:

['my', 'name']
my
My
My

I am wanting it to return both words capitalized.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
amilli91
  • 11
  • 1
  • The function `cap` return after the first word. You need to collect the capitalize words in list and return them – balderman Oct 08 '20 at 21:09
  • `parts = s.split(" ")` creates a list as you can see by splitting the string. Now just loop over that list: `[w.capitalize() for w in parts]` for a list comprehension or `for i, w in enumerate(parts): parts[i] = w.capitalize()` – dawg Oct 08 '20 at 21:16

3 Answers3

1

What about something as simple as:

[s.capitalize() for s in words]

What is happening here?

In short, code complexity optimisation. Rather than writing verbose, (potentially) inefficient code, part of writing quality code is efficiency and readability.

This loop is using a technique called list comprehension. This is a very useful technique when dealing with lists, or for something simple enough to not require a dedicated function.

As words is iterated, the .capitalize() function is called on each word with the results being appended to the returned list - without explicitly appending the list.

To make this into a function, you can use:

def cap(words) -> list:
    """Capitalise each word in a list.

    Args:
        words (list): List of words to be capitalised.

    Returns:
        A list of capitalised words.

    """
    return [s.capitalize() for s in words]

Output:

words = 'my name'.split(' ')
cap(words)

>>> ['My', 'Name']
S3DEV
  • 8,768
  • 3
  • 31
  • 42
1

Why does the program fail?

Have a closer look at your cap() function.

def cap(words):
  for j in words:
    print(j)
    return j.capitalize()

return j.captialize() will exit the function and will only return the capitalized value of the first word.

Correction

The function must capitalize all the elements in the list.

def cap(words):
    capitalized = []
    for word in words:
        capitalized.append(word.capitalize())
    return capitalized

Now the final code should look like

def cap(words):
    capitalized = []
    for word in words:
        capitalized.append(word.capitalize())
    return capitalized

words = ["hello","foo","bar"]
capitalized = cap(words)

print(*capitalized)

perhaps a more pythonic way would be to use a list comprehension

def cap(words):
    return [word.capitalize() for word in words]

words = ["hello","foo","bar"]
capitalized = cap(words)

print("Regular: ",*words) # printing un-packed version of words[]
print("Capitalized: ",*capitalized) 

Output:

Regular: hello foo bar
Capitalized: Hello Foo Bar

0

I have "cleaned" your code (but kept the concept).

Note that it can be done in a much shorter way.

def cap(words):
  result = []
  for j in words:
    result.append(j.capitalize())
  return result

words = "my name"
words_lst = words.split(" ")
capped = cap(words_lst)
result = " ".join(capped)
print(result)

output

My Name

A shorter way :-)

print(' '.join([s.capitalize() for s in 'my name'.split(' ')]))

output

My Name
balderman
  • 22,927
  • 7
  • 34
  • 52