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.
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.
This 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
Now simply call the function split() by providing the argument which has your input string defined (s in our case)
That’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-
Method 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.
Wrapping 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