Click here to Skip to main content
15,888,816 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Write a function that accepts a sentence and capitalize the first letter of each words in the string. You must use split() method to split the sentence into its words

s = caps first letter
Outcome: Caps First Letter

I'm thinking is there any other way to concat the words in print()?

Thank you.

What I have tried:

s = "caps first letter"
str = ""
for word in s.split():
    str = str + " " + word.capitalize()
print(str.lstrip())
Posted
Updated 11-Jun-19 22:43pm

1 solution

Yes, there is.

If you have a list, let's call it words, then you can use print to print those words separated by spaces:
Python
print(*words)
The * operator in this context makes sure that each item in the list gets passed as a different argument to print. So, if words is ['Caps', 'First', 'Letter'], then the code expands to:
Python
print('Caps', 'First', 'Letter')
And because print with multiple arguments prints out each argument separated by spaces, this does exactly what you wanted.

If you would not use the * operator, then the code would expand to this:
Python
print(['Caps', 'First', 'Letter'])
which prints:
Python
['Caps', 'First', 'Letter']
and that's clearly not what you want.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900