Menu
Coddy logo textTech

Iterating Over Strings Part 2

Part of the Fundamentals section of Coddy's Python journey — lesson 63 of 77.

String splitting allows you to break a string into a list, while joining lets you combine list items into a string.

The split() method divides a string into a list of substrings based on a delimiter.

Split by whitespace:

text = "apple banana cherry"
fruits = text.split()
print(fruits)
# ['apple', 'banana', 'cherry']

Split with specific delimiter:

data = "john,25,new york"
data = data.split(',')
print(data)
# ['john', '25', 'new york']

The join() method combines elements of an iterable into a single string.

Basic joining:

words = ['Hello', 'World', 'Python']
text = ' '.join(words)
print(text)
# "Hello World Python"

Join with different separator:

fruits = ['apple', 'banana', 'cherry']
line = ','.join(fruits)
print(line)
# "apple,banana,cherry"
challenge icon

Challenge

Easy

Write a program that takes two inputs: a text string and a delimiter character. The program should split the text by whitespace into words, then join these words using the specified delimited character and print the resulting string.

Cheat sheet

String splitting and joining in Python:

Split a string into a list:

text = "apple banana cherry"
fruits = text.split()  # Split by whitespace
print(fruits)  # ['apple', 'banana', 'cherry']

data = "john,25,new york"
info = data.split(',')  # Split by comma
print(info)  # ['john', '25', 'new york']

Join a list into a string:

words = ['Hello', 'World', 'Python']
text = ' '.join(words)  # Join with space
print(text)  # "Hello World Python"

fruits = ['apple', 'banana', 'cherry']
line = ','.join(fruits)  # Join with comma
print(line)  # "apple,banana,cherry"

Try it yourself

text = input()
delimiter = input()
# Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals