Problem 2.2
Make Header
Write a program header.py
that takes a word as command-line argument and prints it as header as shown below with the word converted to upper case.
$ python header.py python
======
PYTHON
======
$ python header.py python-foundation-course
========================
PYTHON-FOUNDATION-COURSE
========================
Hint:
>>> name = 'python'
>>> name.upper()
'PYTHON'
Solution
import sys
word = sys.argv[1].upper()
n = len(word)
print("=" * n)
print(word)
print("=" * n)
Discussion
The program deals gets the word to print as a command-line argument. So we need to use the sys
module to access the arguments.
import sys
The word will be the first command-line argument and we need to convert it into upper case.
word = sys.argv[1].upper()
Now we need to print a line above and below the word. Line made of =
characters and we use as many of them as the number of characters in the word, so that it aligns well with the word. For that we need to find the length of the word.
n = len(word)
Now, let's print the line above the word.
print("=" * n)
Followed by the word it self.
print(word)
And the line below the word.
print("=" * n)