Video Coming Soon...
8: Formatting Strings Manually
We will now see how to do a more complicated formatting of a string. This code looks complex, but if you do your comments above each line and break each thing down to its parts, you'll understand it.
formatter = "{} {} {} {}"
print(formatter.format(1, 2, 3, 4))
print(formatter.format("one", "two", "three", "four"))
print(formatter.format(True, False, False, True))
print(formatter.format(formatter, formatter, formatter, formatter))
print(formatter.format(
"Try your",
"Own text here",
"Maybe a poem",
"Or a song about fear"
))
What You Should See
1 2 3 4
one two three four
True False False True
{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}
Try your Own text here Maybe a poem Or a song about fear
In this exercise I'm using something called a "function" to turn the formatter variable into other strings. When you see me write formatter.format(...) I'm telling python to do the following:
- Take the
formatterstring defined on line 1. - Call its
formatfunction, which is similar to telling it to do a command line command namedformat. - Pass to
formatfour arguments, which match up with the four{}in theformattervariable. This is like passing arguments to the command line commandformat. - The result of calling
formatonformatteris a new string that has the{}replaced with the four variables. This is whatprintis now printing out.
That's a lot for the eighth exercise, so what I want you to do is consider this a brain teaser. It's alright if you don't really understand what's going on because the rest of the book will slowly make this clear. At this point, try to study this and see what's going on, then move on to the next exercise.
Study Drills
Repeat the Study Drill from Exercise 7.
Common Student Questions
Why do I have to put quotes around "one" but not around
TrueorFalse? Python recognizesTrueandFalseas keywords representing the concept of true and false. If you put quotes around them then they are turned into strings and won't work. You'll learn more about how these work later.Can I use IDLE to run this? No, you should use Jupyter or the command line if you know how. It is essential to learning programming and is a good place to start if you want to learn about programming. Jupyter is a far superior tool than IDLE.
Register for Learn Python the Hard Way, 5th Edition (2023-2024)
Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.