Python Lab · Experiment 19
Add a comma between the characters of a word
PythonWeek 4JNTUH R22 · CS206ES
Aim
To write a Python program that reads a word and prints it with a comma between every pair of characters, so that "Apple" becomes "A,p,p,l,e", using both the join method and a loop.
Algorithm
- Read a word.
- Method 1: use
",".join(word), which puts a comma between the characters of the string. - Method 2: start with an empty result string. For each position i in the word, add a comma first if i is not 0, then add the character.
- Print the results of both methods.
Program
word = input("Enter a word: ")
# Method 1: the join method
with_commas = ",".join(word)
print("Using join :", with_commas)
# Method 2: a loop
result = ""
for i in range(len(word)):
if i > 0:
result = result + "," # comma before every character except the first
result = result + word[i]
print("Using a loop:", result)Output
The word Apple
Enter a word: Apple
Using join : A,p,p,l,e
Using a loop: A,p,p,l,eAnother word
Enter a word: Python
Using join : P,y,t,h,o,n
Using a loop: P,y,t,h,o,nRecorded by running this exact program. Typed input appears after each prompt.
How it works
separator.join(sequence) joins the items of the sequence with the separator between them. A string is a sequence of characters, so ",".join("Apple") puts a comma between each letter. No comma is added before the first or after the last item.
In the loop, the comma is added before each character except the first. Adding it after every character would leave an extra comma at the end, as in A,p,p,l,e,.
Common mistakes
Writing
word.join(","). The separator comes first:",".join(word). The reverse just gives","back, because there is only one item to join.Adding a comma after every character in the loop, which leaves a comma at the end. Add it before every character except the first, or remove the last one with
result[:-1].Trying to change the word in place with
word[i] = .... Strings are immutable in Python, so build a new string instead.
Viva questions
Try to answer each one aloud before you open it.
What does the join method do?
sep.join(items)returns one string made of all the items, withsepplaced between each pair. The items must be strings.Why can't we insert commas into the original string directly?
Strings in Python are immutable: once created they cannot be changed. Every change makes a new string.
What would "-".join(["a", "b", "c"]) give?
"a-b-c".How can you split "A,p,p,l,e" back into characters?
With
"A,p,p,l,e".split(","), which gives['A', 'p', 'p', 'l', 'e']."".joinof that list gives"Apple"again.