Member-only story
Align One Common Letter in Multiple Strings Using One Line of Python Code
A guide on aligning one common letter in multiple strings using one line of Python code.
3 min readApr 11, 2022
Let’s say we are given 1) a list of strings strings
and 2) a letter letter
. Write a one-liner function align(strings, letter)
to print out the strings line by line, aligning letter
vertically.
- If
letter
is not inside a string, don’t print it - If there are more than 1
letter
, use the first one
# Case 1
strings = ["apple", "orange", "pear", "pineapple", ]
letter = "a"# the output: apple
orange
pear
pineapple
banana
Notice that the letter "a"
is aligned vertically in all the strings, and spaces are padded in front of some of the strings in order to align the "a"
.
# Case 2
strings = ["apple", "orange", "pear", "pineapple", "banana"]
letter = "e"# the output: apple
orange
pear
pineapple
Here, e
doesn’t appear in "banana"
so "banana"
is simply not printed. The e
's in other strings are aligned vertically. Also, there are 2 e
's in pineapple
, but we align only the first e
.