Python Program to Separate Characters in a Given String

In this Python programming tutorial, we will be learning to write Python programs to separate the character in a given string. String manipulation is an important aspect of programming. In Python, strings are a sequence of characters and are immutable. Immutable means we cannot modify it once created. In some scenarios, we might be required to separate the characters in a given string. In this tutorial, we will learn various ways to separate characters in a given string using Python.

For Example

Suppose we have a given string

Input

str = "Hello World"

Output will be

H
e
l
l
o

W
o
r
l
d

Program 1: Using a For Loop

Using for loop we can separate the characters from String. We will iterate through each character of the string using for loop and print it on a new line. We have added “\n”, a new line character after printing each character to print them on separate lines. This approach is simple and easy to understand.

str = "Hello Python"
for char in str:
    print(char)
    print("\n")

Output:

H
e
l
l
o

P
y
t
h
o
n

Program 2: Using the Join() Method

Using Join Method we can also separate the characters in a string and then print them on separate lines. In this approach, We will first convert the string into a list of characters using the list() method. After that, we will use the join() method to join all elements in the list. We will add a new line character separator also. After joining we will print the resulting string.

str = "Hello Python"
new_str = "\n".join(list(str))
print(new_str)

Output

H
e
l
l
o

P
y
t
h
o
n

Program 3: Using a Lambda Function

In this Program, we will be using a lambda function to print each character of the string. To achieve this we will use the map() function to apply the lambda function to each character in the string.

str = "Hello Python"
list(map(lambda x: print(x, "\n"), str))

Output

H
e
l
l
o

P
y
t
h
o
n

Conclusion

In this post, we have learned three ways to write a program to separate characters from strings in Python. We have seen using Loop, Join(), and Lambda Function. Overall, all these approaches are valid and achieve the same result. Hope this tutorial was helpful to learn this Python program.