Python | Split and Join Strings

Python’s split and join methods are extremely
useful functions when it comes to manipulating strings and lists. Let’s start with the split method. The split
method “splits” or divides a string into a list. As strings are immutable objects,
meaning that they can not be modified, and lists are mutable objects, meaning that they
can be modified and changed, the split method comes in handy while manipulating strings. Split takes a separator for an argument, meaning
the places where the strings will be split. The default separator is whitespace. If we
split this string we can see that each word is now an individual element in a list. We
can also give any strings as the separator argument for the split method, for example,
a comma. Now, let’s take a look at the join method.
The join method works the opposite way of the split method. It takes an iterable like
a list and joins each element to form a string. Let’s test this out with a list. First, we
declare a string that acts as our separator. In this case, we are using a whitespace. Then
we will use the join method and give our list as an argument. As we can see, the list is
combined into a single string with our separator between each element which now forms words
in a single string. Let’s try both of these methods in a single
use case. Let’s say we want to create a function that takes in a full name as a string with
first name and last name and returns the initials. First, we will create an empty list where
we will append our names. Then we will create a for loop where our iterable will be the
name with the split method. Now we will append the first character of each item with the
upper method which converts the character to an uppercase letter to our names list.
After iterating over the name, and appending the first character of the names to our list,
we will join the initials with “.” as our separator. Let’s pass our function a name, and we can
see that our function generates initials from a full name. For more Python tutorials, like, share, and
subscribe to the PyPros channel.

Leave a Reply

Your email address will not be published. Required fields are marked *