Python

How to Split String into Characters in Python

We have discussed some great stuff on Python so far!

You can check all those in our Python category here.

Today, we are going to talk about how to split string into characters in python. So, basically, we need to create a function (let’s say split()) which help us split string into characters python. If you are new to function, you may check our video on user-defined function here.

Let’s take the below example as what we are looking here. Let’s say we have a string “Hdfs Tutorial” and we want this string to be split into characters in Python. So, basically, we are looking to split string into characters python.

Input: “Hdfs Tutorial”

Output: [‘H’, ‘d’, ‘f’, ‘s’, ‘ ‘, ‘T’, ‘u’, ‘t’, ‘o’, ‘r’, ‘i’, ‘a’, ‘l’]

Let’s start and see this is python!

I am again using Jupyter notebook here but the same code should work in other IDEs as well.

Method 1: split string into characters python using UDF

Here I am creating the function named split() which should take one argument which will be input. Majorly the string which we are looking to split.

define functionThis has created one user-defined function in Python with the name split() which take one argument as input which is a string that we want to split.

Now just define the string we would like to split

define stringNow simply call the function split() by providing the argument which has your input string defined (s in our case)

split string to charactersThat’s it!

This was the easiest method to split string into characters in Python!

There is an N number of methods using which you can do this as well. For example, let’s quickly look into the below methods also.

Method 2:split string into characters python using list()

We can use the simple list() function as well which does the similar work-

string split using list functionMethod 3: split string into characters python using for loop

We can also split a string into characters python using the simple below method where also it does the same string splitting. These methods 2 and 3 are majorly recommended for ad-hoc use and not production ready and repeated work.

string split using for loopWrapping it up!

This was a quick guide on how to split a string into characters in python. We discussed the 3 quick ways to do it. I personally prefer the 1st method by creating a user-defined function as it gives more flexibility.

Leave a Comment