Python | String Split including spaces

Python | String Split including spaces

In this tutorial, we will explore how to split a string into individual characters, including spaces, and store them in a list.

Objective:

Given a string, create a list where each element is a single character from the string, preserving spaces as individual elements.

Example:

For the string "Hello World", the output should be:

['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'] 

Steps:

  • Use List Comprehension: The most straightforward method to achieve this objective is using list comprehension.
input_string = "Hello World" result_list = [char for char in input_string] 
  • Print the Result: Display the resulting list.
print(result_list) 

Output:

['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'] 

Alternative Using the list() Function:

Python's list() function can also be used to convert a string into a list of characters:

input_string = "Hello World" result_list = list(input_string) print(result_list) 

This will produce the same output.

Full Code:

Here's the full code combining the steps using list comprehension:

# Input string input_string = "Hello World" # Convert string into list of characters using list comprehension result_list = [char for char in input_string] # Print the result print(result_list) 

And here's the code using the list() function:

# Input string input_string = "Hello World" # Convert string into list of characters using the list() function result_list = list(input_string) # Print the result print(result_list) 

Notes:

  • When converting a string to a list, spaces are treated as any other character. Therefore, they are preserved in the resulting list.
  • The methods presented here are simple and effective. They can be used whenever you need to break a string into its individual characters, including spaces.

More Tags

apache-commons-beanutils partition poco http-status-code-404 tidyverse database-deadlocks word-wrap character git-fetch cx-oracle

More Programming Guides

Other Guides

More Programming Examples