Split String Into Words Python
Chapter:
Python
Last Updated:
23-09-2023 03:30:36 UTC
Program:
/* ............... START ............... */
# Input string
input_string = "This is a sample string."
# Split the string into words
words = input_string.split()
# Print the words
for word in words:
print(word)
// Another example with a custom delimiter:
# Input string with a custom delimiter (comma)
input_string = "apple,banana,cherry,orange"
# Split the string into words using a comma as the delimiter
words = input_string.split(',')
# Print the words
for word in words:
print(word)
/* ............... END ............... */
Output
// First program output
This
is
a
sample
string.
// Second program output
apple
banana
cherry
orange
Notes:
-
In first example, the split() method is used without any arguments, so it splits the input string into words using whitespace as the delimiter. If you want to split the string based on a different delimiter (e.g., a comma or a hyphen), you can pass that delimiter as an argument to the split() method.
- In second example, the string is split into words using a comma as the delimiter, and the resulting words are printed.