Introduction
Splitting a string into individual words is a common task in text processing. This operation involves breaking down a string into smaller components, typically based on spaces or other delimiters. This tutorial will guide you through creating a Python program that splits a given string into words.
Example:
-
Input:
hello world -
Output:
['hello', 'world'] -
Input:
Python programming is fun -
Output:
['Python', 'programming', 'is', 'fun']
Problem Statement
Create a Python program that:
- Takes a string as input.
- Splits the string into individual words.
- Displays the list of words.
Solution Steps
- Take Input from the User: Use the
input()function to get a string from the user. - Split the String into Words: Use the
split()method to break the string into a list of words. - Display the List of Words: Use the
print()function to display the list of words.
Python Program
# Python Program to Split a String into Words
# Author: https://www.rameshfadatare.com/
# Step 1: Take input from the user
input_string = input("Enter a string: ")
# Step 2: Split the string into words
words = input_string.split()
# Step 3: Display the list of words
print(f"The list of words is: {words}")
Explanation
Step 1: Take Input from the User
- The
input()function prompts the user to enter a string. The input is stored in the variableinput_string.
Step 2: Split the String into Words
- The
split()method is used to break the string into a list of words. By default, this method splits the string at each space and returns a list of words.
Step 3: Display the List of Words
- The
print()function is used to display the list of words.
Output Example
Example 1:
Enter a string: hello world
The list of words is: ['hello', 'world']
Example 2:
Enter a string: Python programming is fun
The list of words is: ['Python', 'programming', 'is', 'fun']
Example 3:
Enter a string: I love coding in Python
The list of words is: ['I', 'love', 'coding', 'in', 'Python']
Conclusion
This Python program demonstrates how to split a string into words using the split() method. It’s a simple and effective way to break down a string into smaller components, which is particularly useful in text processing and analysis. This example helps beginners understand basic string manipulation and list operations in Python.