For this task, we’ll be using a handful of Python techniques in order to split, modify, and rebuild our string so that the first letter in each word is capitalized.
Let’s start with a brief overview of each puzzle piece, so we can review the solution more clearly.
.join()
being an array method — however, in python, it is a string method. The string delimiter is supplied as the base object and the list is passed as an argument to .join()
.Now that we’re more familiar with each piece of the solution, let’s get into it.
We first set our string value and then split it into a list:
message = "hello world"
parts = message.split(" ")
We separate each word by passing an empty space to .split()
. If we were splitting a sequence of comma-separated values the method call would be .split(",")
.
Next, we will use a list comprehension alongside the .capitalize()
method to modify the first letter of each string:
capitalized_parts = [p.capitalize() for p in parts]
What’s happening here is we loop through parts
, assigning each item to the variable p
. Then the resolution of p.capitalize()
is passed to our newly created list.
Finally, we convert from our list back to a string:
capitalized_message = " ".join(capitalized_parts)
This takes some getting used to, but you first supply the delimiter as a string — in our case a blank space — then call the .join()
method with the list as an argument.
So far we’ve moved one step at a time for clarity. However, the entire solution can be condensed into a single statement — awesome, right?
message = "hello world"
capitalized_message = " ".join([
word.capitalize()
for word in message.split(" ")
])
print(capitalized_message) # Hello World
If you are inclined to do so, you could easily take this statement and create a function that accepts two arguments — the string and the delimiter — to reuse when necessary.
☞ Python Tutorials for Beginners - Learn Python Online
☞ Learn Python in 12 Hours | Python Tutorial For Beginners
☞ Complete Python Tutorial for Beginners (2019)
☞ Python Programming Tutorial | Full Python Course for Beginners 2019