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
EasyWrite 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.
Try it yourself
text = input()
delimiter = input()
# Write your code belowThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 48Loops
For LoopWhile LoopBreakContinueRecap - FactorialThe Range FunctionNested LoopRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators9Functions
Declare a FunctionArgumentsReturnRecap - Sigma FunctionRecap - Validation FunctionDefault Values12Iterating Over Sequences
Iterating Over ElementsThe Enumerate FunctionIterating Over Strings Part 1Iterating Over Strings Part 2